Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-python like button
Hi lads I want to add like button to make project. but getting error. Exception Value: Reverse for 'like_recipe' with arguments '('',)' not found. 1 pattern(s) tried: ['add_recipe/like/(?P[0-9]+)/\Z']enter image description here[[enter image description here](https://i.stack.imgur.com/My5IO.png)](https://i.stack.imgur.com/AR7Uy.png) I didn't try anything as I cant understand were i problem -
Enforcing row level permission in Django Models
I am trying to enforce row (object) level permissions in Django, on the model level. All the resources on the web revolve around two possible solutions: Option 1. Passing the request manually to a custom manager with a for_user() method: # manager class EntryManager(models.Manager): def for_user(self, user): return self.get_queryset().filter(owner=user) # model class Entry(models.Model): owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) objects = EntryManager() # usage in views/serializers/forms/admin/... Entry.objects.for_user(request.user) Option 2: Using threading.local() variables to store the request/user in the middleware, and than access them in the model. Examples: https://github.com/benrobster/django-threadlocals https://github.com/Alir3z4/django-crequest https://www.viget.com/articles/multi-tenancy-in-django/ I don't like option 1, because it relies on a developer calling a for_user() method, which can be often forgotten. There are a lot of people on the internet that don't like option 2, because of the usage of threadlocals and also because of a Django philosophy that models should be request-unaware. I am coming from a framework such as Laravel which allows access to the Request and User at all levels, so I am puzzled why this is a no-no in Django. I did take a look at django-guardian as well, but the module seems quite complex, and no easy way to filter out all objects linked to a user. Also … -
How to style grouped checkboxes from CheckboxSelectMultiple in django with crispy_form
Here is my form: class MyForm(forms.ModelForm): foo = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class': 'flat'})) class Meta: model = MyModel exclude = ['bar', 'baz'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) choices = ( ('Groupe1', ( (1, 'Item1'), (2, 'Item2'), )), ('Groupe2', ( (1, 'Item1'), (2, 'Item2'), )), ) self.fields["foo"].choices = choices self.helper = FormHelper(self) self.helper.form_id = 'myform_id' self.helper.form_class = 'myform_class' self.helper.form_method = 'GET' self.helper.use_custom_control = True self.helper.label_class = 'font-weight-bold' Once rendered, I would like to change the style of the group labels. But I don't know how to access it. When I inspect my form, I see the structure looks like this: <form> <div class="form-group"> <div class="controls"> <strong>Groupe1</strong> <div class="checkbox"> <label class="" for="id_actes_select_0_0"> <div class="icheckbox_flat-green" style="position: relative;"> <input type="checkbox" name="foo" value="Item1" class="flat" id="id_actes_select_0_0"> </div> Item1 </label> </div> ... </div> </div> </form> Group labels are wrapped in strong tags. I would like to style them in css. How to do it with crispy_form ? -
Subtract two quantities value from two different class model in Django
I am trying to do a subtraction from Add_Purchase model to Received_Payment check how many payment received against selected User PK and check if payment not received 100% remaining payment show in HTML form can you please confirm me any one which function use in views.py file I'll share our model here according to above given question thanks. class Add_Purchase(models.Model): date_of_purcahse = models.DateField() supplier_info = models.ForeignKey(add_supplier, on_delete=models.CASCADE) product_type = models.ForeignKey(Product_Type, on_delete=models.CASCADE) product_item = models.ForeignKey(Product_Item, on_delete=models.CASCADE) product_price = models.CharField(max_length=100) product_qty = models.CharField(max_length=100) bill_num = models.CharField(max_length=100) def __str__(self): return self.supplier_info class Received_Payment(models.Model): monthly_inst = models.DecimalField(max_digits=10, decimal_places=2, null=True) client_name = models.ForeignKey(Add_Buyer, on_delete=models.CASCADE) item_payment_received = models.ForeignKey(Cridet_Sale, on_delete=models.CASCADE) payment_date = models.DateField() slip_number = models.CharField(max_length=50) def __str__(self): return str(self.payment_date) -
Permission denied: mod_wsgi, when using mod_wsgi with apache2 and pyenv
I was trying to deploy django app using mod_wsgi (version=4.9.4), apache2 and pyenv, also created the python virtual-env using pyenv, here is the apache configuration used <VirtualHost *:80> ServerName dev.<domain>.com WSGIDaemonProcess dev.<domain>.com python-home=<path><to><pyenv-virtualenv> python-path=<projectdir> WSGIProcessGroup dev.<domain>.com WSGIApplicationGroup %{GLOBAL} ErrorLog "${APACHE_LOG_DIR}/timesheet_internal.log" CustomLog "${APACHE_LOG_DIR}/timesheet_internal.log" common LogLevel Warn Alias /static /var/www/<projectpath>/static <Directory /var/www/<projectpath>/static> Require all granted </Directory> Alias /.well-known/acme-challenge/ "/var/www/<projectpath>/.well-known/acme-challenge/" <Directory "/var/www/<projectpath>/"> AllowOverride None Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec Require method GET POST DELETE PATCH OPTIONS </Directory> WSGIScriptAlias / /var/www/<path>/wsgi.py <Directory "/var/www/<path>/wsgi.py"> Require all granted </Directory> </VirtualHost> <pyenv-virtualenv>/bin/python manage.py --collectstatic --no-input --clear and <pyenv-virtualenv>/bin/python manage.py migrate --no-input both these commands are executed successfully and the app also worked in my local, but on deploying in ec2(ubuntu 22.04) the application ran into following errors [Mon Jun 12 14:17:51.520596 2023] [wsgi:warn] [pid 1224676:tid 140062563575680] (13)Permission denied: mod_wsgi (pid=1224676): Unable to stat Python home /home/ubuntu/.pyenv/versions/3.11.3/envs/timesheet_env. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/ubuntu/.pyenv/versions/3.11.3/envs/timesheet_env' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 safe_path = 0 import site = 1 is in build tree = 0 stdlib dir … -
facing Python Package version issues
I am trying to run an old django project which was build on python 3.6. currently I am using venv with python 3.10 & below is my list of dependencies mysqlclient==1.3.13 arrow==0.12.1 gunicorn==19.9.0 pymongo==3.7.1 pytrends==4.4.0 Faker==0.9.1 newsapi-python==0.2.3 progressbar2==3.38.0 newspaper3k==0.2.7 requests==2.17.1 beautifulsoup4==4.6.3 selenium==3.14.0 lxml==4.2.5 pandas==0.23.4 langdetect==1.0.7 pyjwt==1.6.4 msgpack==0.5.6 bpython==0.17.1 xlsxWriter==1.1.1 feedparser==5.2.1 querystring-parser==1.2.3 google_images_download==2.5.0 xlrd==1.2.0 algoliasearch==2.0.4 PyMySQL==0.9.3 fuzzywuzzy==0.17.0 python-levenshtein==0.12.0 firebase-admin==4.3.0 can any one suggest me package version for smooth project run? -
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': …