Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Save Received dictionary Data into Django DataBase?
views.py file I'm using paytm payment gateway here, I want to save data into database in response view but Im getting data in dict form how do I access individual and pass into user.email field def payment(request): user = request.user order_id = Checksum.__id_generator__() bill_amount = request.GET['money'] data_dict = { 'MID': settings.PAYTM_MERCHANT_ID, 'INDUSTRY_TYPE_ID': settings.PAYTM_INDUSTRY_TYPE_ID, 'WEBSITE': settings.PAYTM_WEBSITE, 'CHANNEL_ID': settings.PAYTM_CHANNEL_ID, 'CALLBACK_URL': settings.PAYTM_CALLBACK_URL, 'CUST_ID': user.email, 'ORDER_ID':order_id, 'TXN_AMOUNT': bill_amount, } # This data should ideally come from database data_dict['CHECKSUMHASH'] = Checksum.generate_checksum(data_dict, settings.PAYTM_MERCHANT_KEY) context = { 'payment_url': settings.PAYTM_PAYMENT_GATEWAY_URL, 'comany_name': settings.PAYTM_COMPANY_NAME, 'data_dict': data_dict, } return render(request, 'payment.html', context) def response(request): if request.method == "POST": MERCHANT_KEY = settings.PAYTM_MERCHANT_KEY CUST_ID = request.POST['CUST_ID'] data_dict = {} for key in request.POST: data_dict[key] = request.POST[key] if data_dict.get('CHECKSUMHASH', False): verify = Checksum.verify_checksum(data_dict, MERCHANT_KEY, data_dict['CHECKSUMHASH']) else: verify = False if verify: for key in request.POST: if key == "BANKTXNID" or key == "RESPCODE": if request.POST[key]: data_dict[key] = int(request.POST[key]) else: data_dict[key] = 0 elif key == "TXNAMOUNT": data_dict[key] = float(request.POST[key]) PaytmHistory.objects.create(user = User.objects.only('user_id').get('user.email' == CUST_ID).user_id, **data_dict) return render(request, "callback1.html", {"paytm": data_dict}) else: return HttpResponse("checksum verify failed") else: return HttpResponse("Method \"GET\" not allowed") return HttpResponse(status=200) waiting for help -
What I am missing in the setup of nginx with gunicorn which leads to 502 error?
I am setting up django + gunicorn + nginx on my local (mac os) to test some nginx reverse proxy configuration. I have gone through few tutorials about the setup of these. I have a doubt: Everywhere in tutorials they run gunicorn as daemon or service. Why is it necessary? cant we just run gunicorn in a shell binding it to a port (which will be listened by nginx) My gunicorn.conf.py file: import os bind = '0.0.0.0:8080' errorlog = '-' worker_class = 'gthread' workers = 2 threads = 3 timeout = 60 max_requests = 25 max_requests_jitter = 3 preload_app = True worker_connections = 5 keepalive = 65 running gunicorn using : gunicorn --conf gunicorn.conf.py my-project.wsgi:application nginx nginx.conf: upstream test { server localhost:8080; keepalive 32; keepalive_timeout 65s; } server { listen 80; proxy_http_version 1.1; proxy_connect_timeout 5s; proxy_send_timeout 10s; proxy_read_timeout 20s; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; location / { proxy_pass http://test; } } then I run this nginx conf using nginx docker creating image from DockerFile: FROM nginx:alpine COPY nginx.conf /etc/nginx/conf.d/default.conf Then running the image by: docker run --rm -p 3030:80 --name test-server <image-name> after these localhost:8080 serves my django project through unicorn but localhost:3030 (nginx … -
Pandas 1.2 Update - pd .read_excel no longer imports file from form - Path Error
I am using Django to select an Excel (xlsx) file from a form. (This is a Foundation html.) <form action="{% url "edit:add_trades" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="FileUpload" class="button">Upload File</label> <input type="file" id="excel_file" class="show-for-sr"> </form> Before using Pandas 1.10 and xlrd 1.2 all worked well with this code: This is the view code: if request.method == 'POST': file = request.FILES [ 'excel_file' ] file_name, file_type = os.path.splitext ( file.name ) // check for xlsx file type if str ( file_type ) != '.xlsx': msg = "Sorry, not a .xlsx file." messages.warning ( request, msg ) return redirect ( '/edit/index' ) # get the excel data df = pd.read_excel ( file, sheet_name = 'orders', index_col = None, header = None ) When I update to pandas 1.2 I get a file error: FileNotFoundError at /edit/add_trades/ [Errno 2] No such file or directory: '63P-11955.xlsx' Request Method: POST Django Version: 2.2.16 Exception Type: FileNotFoundError I also get this error when updating the xlrd. What changed in this Pandas update and the path from a Django form? Using python 2.8 and Django 2.2.16. Thank you. -
Issue When Running Django Migrations on MariaDB 10.5.8
I have been trying to migrate from a mysql database (version 5.7.26-29-31.37-log - output from SELECT VERSION()) to a mariadb (version 10.5.8-MariaDB-log - output from SELECT VERSION()) Also, I saw and updated django from version 2.2 to version 3.1.5, as mariadb is officially supported from version 3.0. With this, I also updated the mysqlclient library to 2.0.3. But when on the server the "migrate" command is run, it fails with this error when doing it with the new DB: decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>] Here is the stack-trace: DEBUG (0.008) SELECT @@SQL_AUTO_IS_NULL; args=None DEBUG (0.007) SHOW FULL TABLES; args=None DEBUG (0.007) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None DEBUG (0.008) SHOW FULL TABLES; args=None OUT Operations to perform: OUT Apply all migrations: admin, auth, contenttypes, my_auth, essay, multichoice, quiz, sessions, sites, social_django, true_false OUT Running pre-migrate handlers for application auth OUT Running pre-migrate handlers for application contenttypes OUT Running pre-migrate handlers for application sessions OUT Running pre-migrate handlers for application sites OUT Running pre-migrate handlers for application admin OUT Running pre-migrate handlers for application quiz OUT Running pre-migrate handlers for application multichoice OUT Running pre-migrate handlers for application true_false OUT Running pre-migrate handlers for application essay OUT Running pre-migrate handlers for … -
I am trying to search the student result using registration# ? Help appricated
need help to search the data, when I enter the registration number it is not giving me the details which I have typed in the admin page. need help ??? home.html I don't know how to place data for display and also in other stuff. moodle.py from django.db import models from django.utils.encoding import smart_text class ResultQuery(models.Model): name=models.CharField(max_length=150) dept_name=models.CharField(max_length=200) cgpa=models.CharField(max_length=50) reg_number=models.CharField(max_length=100) def __str__(self): return smart_text(self.name) app==> url.py from django.urls import path from . import views urlpatterns = [ path('', views.home), ] forms.py from django import forms class ResultForm(forms.Form): Reg_No =forms.CharField(label="Registration Number") views.py from django.shortcuts import render # Create your views here. from django.shortcuts import render from .forms import ResultForm from .models import ResultQuery def home(request): form=ResultForm(request.POST or None) template_name = "home.html" context = {"form": form} if form.is_valid(): objects = ResultQuery.objects.filter(reg_number=form.cleaned_data['Reg_No']) context['objects'] = objects return render(request, template_name, context) admin.py from django.contrib import admin from .models import ResultQuery # Register your models here. admin.site.register(ResultQuery), home.html <h1>Search Your Result</h1> <form method="POST" action=" "> {% csrf_token %} {{ form }} <input type="submit" value="Submit"/> </form> Note: I would like to do the search and display the data, help me in HTML page also. screenshots for reference. -
Django : Why is my submit interest form not submitted. Did I write my view or template wrongly?
Django : Why is my submit interest form not submitted. Did I write my view or template wrongly? Based on the view I wrote, I dont even get redirected after I click on submit. And when i return to the home page, i Receive a message from here messages.warning(request, 'Something went wrong. Please try again..', extra_tags='wronginterest') which is why I believe it is because the form is not valid thats why it is not submitting. but wth why is it not valid?? Thanks views.py def submit_interest_view(request, slug): user = request.user blog_post = BlogPost.objects.get(slug=slug) num_blogpost = BlogPost.objects.filter(author=request.user).count() if not user.is_authenticated: return redirect('must_authenticate') elif blog_post.author == request.user: return HttpResponse('You cannot submit interest to your own post.') interest_requests = Interest.objects.filter(interestsender=request.user, interestreceiver=blog_post.author) for interest_request in interest_requests: if interest_request.is_active: return HttpResponse('You have already submitted your interest to this post.') if request.method == 'POST': # use request.method == 'POST' to submit POST request (like submitting a form) form = SubmitInterestForm(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit=False) author = Account.objects.get(email=user.email) # use get if you aim to get a single object not a queryset obj.author = author obj.blog_post = blog_post obj.save() messages.success(request, 'Your interests have been submitted', extra_tags='submittedinterest') context['success_message'] = "Updated" if request.META.get('HTTP_REFERER') == request.build_absolute_uri(reverse("HomeFeed:main")): return redirect(reverse("HomeFeed:main")) … -
Django DjangoFilterBackend filter with OR condition in url params?
I have following class. class PersonListView(generics.ListAPIView): serializer_class = PersonSerializer permission_class = permissions.IsAuthenticatedOrReadOnly filter_backends = (DjangoFilterBackend,) filterset_fields = { 'city': ['exact'], 'age': ['gte', 'lte', 'exact', 'gt', 'lt'], 'param_1': ['exact'], 'param_2': ['exact'], 'param_3': ['exact'], 'param_4': ['exact'], 'param_5': ['exact'], } How to perfom filter with OR condition in ulr params? For example following url http://127.0.0.1:8000/api/persons/all?city=Novosibirsk&param_1=25 searches records with city Novosibirsk AND param_1 = 25. But i want to filter with OR condition. -
How do I capture the state of an object in Django?
I have developed a web app in Django to record sales in a retail store. I have the following two models in my project: class Product(models.Model): code = models.CharField(max_length=256) name = models.CharField(max_length=256) description = models.CharField(max_length=2048) cost_price = models.DecimalField(max_digits=8, decimal_places=2) retail_price = models.DecimalField(max_digits=8, decimal_places=2) class Sale(models.Model): date = models.DateTimeField(default=timezone.now) product = models.ForeignKey(Product, on_delete=models.CASCADE) The problem I'm having is that when I edit the price on the product, it will also affect past sales of that product. This is because the product is a foreign key on the sale model. What is the best method to ensure that all sales are not affected by any edits on the product? I thought about adding a price field on the sale model to ensure that the price remains static, like so: class Sale(models.Model): date = models.DateTimeField(default=timezone.now) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=8, decimal_places=2) However, I'm not sure if this is the best solution, it seems hard coded in a way. I would appreciate any advice. -
Is react or any front end needed with good django project?
I had started making a social webapp using django...and ofcourse i did it but when i look back at my code its very lengthy i have used ajax everyehere i dont have to reload the page like (like,comment,rating)... is there any good option in django rather than writing too much of javascript or do i need to use react...(What about django async ?) or the only way is using (django rest framework and react) please let me know because i am thinking like it will be more tool than tecnique if i learn both -
Django Celery create task with JS microservice
Hello I have a Django app running celery, and I'm trying to add tasks to the queue using a microservice in JS. When I add the task though Django everything works fine, but when I use JS i get this error: [2021-01-05 19:39:55,982: WARNING/MainProcess] Received and deleted unknown message. Wrong destination?!? The full contents of the message body was: body: '{"expires":null,"utc":true,"args":[5456,2878],"chord":null,"callbacks":null,"errbacks":null,"taskset":null,"id":"1a361c85-2209-4ffa-95c2-ee2e4855155e","retries":0,"task":"config.celery.debug_task","timelimit":[null,null],"eta":null,"kwargs":{}}' (244b) {content_type:None content_encoding:None delivery_info:{'sqs_message': {'MessageId': '7b7d2948-c069-4f8b-9fdc-9c068d52f463', 'ReceiptHandle': 'AQEBxhqW2sRWf+Z851fw7nqRX6MQFVcTfjH5xqiIgYIiMa3AN3R235VxhM8pM7mcByw3eOZ3Y7kH5oZ+noFVzfjSllgnoh8idB/V7WWY2urNHKJrQadRT5cf4NcUVkFmB8+d2rLiAXuuyqpGbEMvmx1Dn49/5C3Fx8Eq+eUyB1oeilIrCqfMvIkG/yX5TdedxM9B2VBThZ/XtHqrgYCkJvEt9ozssM0f+INRHUrpVQMYCmUX9aTWeWljrTOapMTg27M6aie6HaDQxLK0FJvZUNr2d0uJhZ4C2qRGWrSo2VpD7QK7pslltZ12PVHKPw9X+cBGdWwJrdh5I0fBITuoy+CUUnybDekz668jJnsf1gcmpx8cBoVrMLocPi753g2klGf++mbFeL7yjENzb1YqZrrfvg==', 'MD5OfBody': '9bb39da667d1e840f8532a74a8dcecaa', 'Body': 'eyJleHBpcmVzIjpudWxsLCJ1dGMiOnRydWUsImFyZ3MiOls1NDU2LDI4NzhdLCJjaG9yZCI6bnVsbCwiY2FsbGJhY2tzIjpudWxsLCJlcnJiYWNrcyI6bnVsbCwidGFza3NldCI6bnVsbCwiaWQiOiIxYTM2MWM4NS0yMjA5LTRmZmEtOTVjMi1lZTJlNDg1NTE1NWUiLCJyZXRyaWVzIjowLCJ0YXNrIjoiY29uZmlnLmNlbGVyeS5kZWJ1Z190YXNrIiwidGltZWxpbWl0IjpbbnVsbCxudWxsXSwiZXRhIjpudWxsLCJrd2FyZ3MiOnt9fQ=='}, 'sqs_queue': 'SQS_QUEUE_URL_HERE'} headers={}} I am using this code to send the msg: let taskId = uuidv4(); let result = { "expires": null, "utc": true, "args": [5456, 2878], "chord": null, "callbacks": null, "errbacks": null, "taskset": null, "id": taskId, "retries": 0, "task": "config.celery.debug_task", "timelimit": [null, null], "eta": null, "kwargs": {} } const client = new SQSClient({ region: "eu-west-3", credentialDefaultProvider: myCredentialProvider }); const send = new SendMessageCommand({ // use wrangler secrets to provide this global variable QueueUrl: "SQS_QUEUE_URL_HERE", MessageBody: Buffer.from(JSON.stringify(result)).toString("base64") }); let resultSQS = client.send(send); I debugged the django task payload to copy it, so I'm sending the same data it needs, but getting this error. Anyone knows if I'm missing something? Thanks -
how to store google signin details into database dbsqlite3 in python django, details includes token id,name,maild
It is not able to store details i get from google signin into db sqlite table.how to insert google signin datas this into dbsqlite in python django,details include token id,name,email id.please help me to do this. 0 const fillValues = () => { const welcome = document.getElementById("welcome"); let url_string = window.location.href; // to get current window location path let url = new URL(url_string); // convert the string as a new url let details = url.searchParams.get("details"); // for getting parameters from url details = JSON.parse(details); // convert string to object let image = document.getElementById("userImg").src = details.imgUrl; welcome.textContent = "Heyy "+details.name + ",login is successfull. Your Email is :" + details.email + ". And your Id is " + details.id; }; window.onload = fillValues; <head> <meta name="google-signin-scope" content="profile email"> <meta name="google-signin-client_id" content="119401361204-mvi8rs8iv0kpff5c731v5ie2m7go00lr.apps.googleusercontent.com"> <script src="https://apis.google.com/js/platform.js" async defer></script> </head> <body> <div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div> <script> function onSignIn(googleUser) { // Useful data for your client-side scripts: var profile = googleUser.getBasicProfile(); console.log("ID: " + profile.getId()); // Don't send this directly to your server! console.log('Full Name: ' + profile.getName()); console.log('Given Name: ' + profile.getGivenName()); console.log('Family Name: ' + profile.getFamilyName()); console.log("Image URL: " + profile.getImageUrl()); console.log("Email: " + profile.getEmail()); // The ID token you need to pass to … -
Count all category objects in a filtered querry in django?
I am desperately trying to count the objects in a category in my model. To be more clear: I am scraping news articles and I have this model: class News(models.Model): title = models.CharField(max_length=2000) link = models.CharField(max_length=2083, default="", unique=True) published = models.DateTimeField() desc = models.CharField(max_length=2083) site = models.CharField(max_length=30, default="", blank=True, null=True) and this view filtering objects and serving them upon request: class SearchResultsView(ListView): model = News template_name = 'search_results.html' context_object_name = 'articles' def get_queryset(self): query = self.request.GET.get('q') min_dt = self.request.GET.get('qf') max_dt = self.request.GET.get('qt') object_list = News.objects.filter(Q (title__icontains=query)| Q (desc__icontains=query) & Q (published__range=(min_dt, max_dt))).order_by('-published') I need to put on my html django website how many articles I get for each site Here is my html <div class="row"> <table> <tbody> <h2>{{ articles.count }} articles found in total </h2> HERE I NEED TO PUT HOW MANY ARTICLES PER SITE BELOW IS THE ACTUAL LIST ON A TABLE {% for a in articles %} <tr> <td> <a href="{{ a.link }}">{{ a.title }}</a> </td> <td> <p> Source: {{ a.site }} </p> </td> <td> <p> Published: {{ a.published }} </p> </td> <td> <p> More info: {{ a.desc }} </p> </td> </tr> {% endfor %} </tbody> </table> -
Django rest framework serializer validation error messages in array
Is there a way to get array of error messages instead of object when retrieving validation errors from serializers? For example: [ "User with this email already exists.", "User with this phone number already exists." ] Instead of: { "email": [ "User with this email already exists." ], "phone_number": [ "User with this phone number already exists." ] } -
Django auth +MySQL migrations, row size too large
This migration file fails which is included in the contrib.auth /Users/xxx/.virtualenvs/xxxx-0LdyW30-/lib/python3.8/site-packages/django/contrib/auth/migrations/0012_alter_user_first_name_max_length.py from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ migrations.AlterField( model_name='user', name='first_name', field=models.CharField(blank=True, max_length=150, verbose_name='first name'), ), ] error: web_1 | MySQLdb._exceptions.OperationalError: (1118, 'Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs') note: I'm using a docker-compose environment -
Django: Is There A Way To Refresh Page Without Going Back To The Top Of The Page
I am using a like button but everytime i press it it needs to refresh the page which sends the user back to the top of the page. I want to find a way to refresh the page but keep the position at the post they liked. Is there a good way to do this. I know it can be done because most social media sites do this. views.py: def like_post(request, pk): post = Post.objects.get(id=pk) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('home-new')) -
How to get one to many like result in a queryset
How to achieve one to many like result in a queryset. I am doing a query that returns results that match checkout date. Is it possible to modify the result so as to return array of rooms under one ref_id where the ref_id and checkout date is matching?. # models.py class Booking(models.Model): ref_id = models.TextField(null=True) room = models.ForeignKey(Room, on_delete=models.SET_NULL, null=True) check_in_date = models.DateField(blank=False, null=False) check_out_date = models.DateField(blank=False, null=False) # serializer.py class RoomSerializer(serializers.ModelSerializer): class Meta: model = Room fields = ('id', 'room_number',) class BookingsSerializer(serializers.Serializer): ref_id = serializers.CharField() room = serializers.ListField(child=RoomSerializer()) # room = RoomSerializer(many=True) check_out_date = serializers.DateField() # views.py class ReadBookings(APIView): filter = {} filter['check_out_date']=check_out_date bookings = Booking.objects.filter(**filter) serializer = BookingsSerializer(bookings,many=True) return Response(serializer.data) enter code here Returned result [ { id: 1 ref_id: "o6eWRjURKP-e4c6d0ca96a145419f528db1a9994029-1609055850117" check_out_date: "2020-12-29" room:{ id: 8 room_number: "006" }, { id: 2 ref_id: "o6eWRjURKP-e4c6d0ca96a145419f528db1a9994029-1609055850117" check_out_date: "2020-12-29" room:{ id: 9 room_number: "007" } ] Desired result [ { id: 1 ref_id: "o6eWRjURKP-e4c6d0ca96a145419f528db1a9994029-1609055850117" check_out_date: "2020-12-29" rooms:[ { id: 8 room_number: "006" }, { id: 9 room_number: "007" } ] }, { ......... ..... } ] -
Django: Invalid block tag on line 14: 'endblock', expected 'endfor'. Did you forget to register or load this tag?
I am a new python learner and I am currently going through Chapter 19 of Python Crash Course edition and I am encountering this problem with topics.html file Django: Invalid block tag on line 14: 'endblock', expected 'endfor'. Did you forget to register or load this tag? My topics.html file looks like this: {% extends "learning_logs/base.html" %} {% block content %} <p>Topics</p> <ul> {% for topic in topics %} <li> <a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a> <li> {% empty %} </ul> <a href="{% url 'learning_logs:new_topic' %}">Add a new topic</a> {% endblock content %} The Line 14 which it was referring to was this: {% endblock content %} I searched for similar tickets like this and I thought it was the spacing in that line. I edited it and I still get the same issue. I checked the rest of the file and it seems to follow the proper spacing of the { and %. Please help me figure this one out. Would greatly appreciate it. -
Packages to share contents on social media with Django Rest Framework
My app uses a Django backend and vuejs frontend, with API's served with Django Rest Framework. Now at the front end, I need to add social media links to share my contents on social media, notably Facebook, Instagram and Twitter. I have tried googling around for a resource but can't seems to find any, except django-rest-auth and allauth packages which work for authentication, not sharing. I will appreciate if anyone can direct or guide me to packages I can use for this purpose? -
"no such column adoptions_pet.submissions.date" error
Doing the "Become a Django dev" on LI Learning. However, I have trouble getting the column date values of a .csv into my website. Any help appreciated. If I don't formulate the problem well for you to help me, please let me know what extra information I should give. The error goes, after visiting http://localhost:8000/admin/adoptions/pet/: File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: adoptions_pet.submissions_date The db.sqlite3 file looks fine in my DB browser. db browser image models.py file: from django.db import models class Pet(models.Model): SEX_CHOICES = [('M', 'Male'), ('F', 'Female')] name = models.CharField(max_length=100) submitter = models.CharField(max_length=100) species = models.CharField(max_length=30) breed = models.CharField(max_length=30, blank=True) description = models.TextField() sex = models.CharField(max_length=1, choices=SEX_CHOICES, blank=True) submissions_date = models.DateTimeField() age = models.IntegerField(null=True) vaccinations = models.ManyToManyField('Vaccine', blank=True) class Vaccine(models.Model): name = models.CharField(max_length=50) load.pet.data.py from csv import DictReader from datetime import datetime from django.core.management import BaseCommand from adoptions.models import Pet, Vaccine from pytz import UTC DATETIME_FORMAT = '%m/%d/%Y %H:%M' VACCINES_NAMES = [ 'Canine Parvo', 'Canine Distemper', 'Canine Rabies', 'Canine Leptospira', 'Feline Herpes Virus 1', 'Feline Rabies', 'Feline Leukemia' ] ALREDY_LOADED_ERROR_MESSAGE = """ If you need to reload the pet data from the CSV file, first delete the db.sqlite3 file to destroy … -
How to Call A Particular Relational Field in Django 3.*
I have two models like so: class model1(model.Models): a=model.ForeignKey('model2') // the goal is to call only value **c** that is present in model2 class Model2(model.Models): b=some codes c= some codes What I am trying to do is that anytime I call a in the template.html, then {{a}} should render value of c that is in Model2 Please is there any parameter that exists in django3 for this to work? -
How to do migratiobn in django?
Initially I migrated one app models after that I added one field there pol_id = CharField(max_length=25, unique=True) now if I am running makemigrations its showing me You are trying to add a non-nullable field 'pol_id' to Health without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py In my db there is no any object, I saw many answer to put there null=True, but I can't add null=True in pol_id, is there any hard migration command to fix this issue? -
How do I send email through button click in django?
I am a beginner in Django. I can not go to the view via ajax code. I have coded it at the button click. This code was written to send an email through button click. In view.py, while code in def error displayed and otherwise if code in class email sent when document load . Email should be sent on button click. Can you help me with that? user_profile.html <button class="btn btn-orange" id="btn_delete" onclick="delete_profile1()">Delete</button> <script> function delete_profile1() { $.ajax({ type: 'POST', url: '{% url "delete_profile" %}', data: { }, success: function () { toastr.info('Preference Updated Successfully') } }); } </script> urls.py path('delete_profile', delete_profile.as_view(), name='delete_profile'), views.py class delete_profile(View): def post(self, request, *args, **kwargs): print("nothing") template = loader.get_template("frontend/subscription-start.html") email_content = "deletion confirmation" send_mail( 'No Dowry Marriage - Subscription', email_content, 'developer@goodbits.in', [rihla1995@gmail.com], html_message=email_content, fail_silently=False ) -
how to manage the folder for media files in production environment?
I have my Django-app and I am using fileSystemStorage to store my media files and now I want to deploy my app on heroku. But the problem is that my code for media file storage is as follows: urls.py if settings.DEBUG: urlpatterns + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) settings.py . . # Upload Media Files MEDIA_URL = '/uploads/' MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') . . And in production mode we have to set "DEBUG to FALSE" which will produce a problem for storing the files. Can you suggest some ways to deal with this issue? Ps: I know that FileSystemStorage shouldn't be used in production environment but it's fine for my case since I'm using it to store files temporarily. -
how to not redirect to other page after JsonResponse in django?
I have 2 views which are post_detail_view and login_function. I use post_detail_view to render login form and login_function to handle POST request. # views.py def tutorial_detail_view(request, pk): context = {} context['object'] = TutorialPost.objects.get(id = pk) context['login_form'] = LoginForm() return render(request, "tutorial/tutorial_detail.html", context) def login_function(request): if request.method == "POST": login_form = LoginForm(request.POST) if login_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email = email, password = password) if user is not None: login(request, user) return JsonResponse({'success': True}, status=200) else: return JsonResponse({'form_errors': login_form.errors}, status=400) return JsonResponse({}, status=400) # urls.py path('post/<slug:pk>/', tutorial_detail_view, name="tutorial_detial"), path('login/', login_function, name="login") # tutorial_detail.html <form action="{% url 'login' %}" method="POST"> {% csrf_token %} {{ login_form.email }} {{ login_form.password }} <button type="submit">log in</button> </form> What I want is to get response or error response from JsonReponse and stay in tutorail_detail.html and post/<slug:pk> url and I have some javascript code to get that response but it keeps redirecting me to login url and display response there. How can i fix it? -
how can i use Django with html CSS JS?
I am making a website and through some sources ,I find out that Django is for backend and html CSS and JS is for front end ,so I am designing my pages in the later 3 and not started developing the backend so, is there any way that I can use Django with html CSS and JS? (please suggest an easy method as I am a newbie ,however I am quite familiar with python )