Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding content_type to render_to_response in Django's views.py causing 'Server Error (500)'
In django 1.11, in views.py I am using the render_to_response function as follows: return render_to_response(domainObject.template_path, context_dict, context) This works fine. Now I am trying to specify the content_type for this response as 'txt/html'. So I switch to content_type = 'txt/html' return render_to_response(domainObject.template_path, context_dict, context, content_type) But with this setup the server returns a Server Error (500) Following the documentation at https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render-to-response I think I am providing the variables in the right order... Here is the full 'def' block for reference: def myview(request): context = RequestContext(request) if request.homepage: migrationObject = calltomigration() else: integrationObject = Integration.objects.filter(subdomain_slug=request.subdomain).get() except ObjectDoesNotExist: logger.warning(ObjectDoesNotExist) raise Http404 sectionContent = None if not request.homepage: sectionContent = getLeafpageSectionContent(referenceObject) context_dict = { 'reference': referenceObject, 'sectionContent': sectionContent, 'is_homepage': request.homepage } # content_type = 'txt/html' return render_to_response(domainObject.template_path, context_dict, context) -
How can I refresh only the child page that contains a form in Django environment
I've been working on a Django form. The form is in the poc_add.html site. The index.html side contains the <div id="output"></div> that is being filled out with the poc_add.html content. In other words the poc_add.html site is a part of the index.html site. Here is the code of the form: <form class="form"> {% csrf_token %} <fieldset> <label class="mb-0" for="cmbLocation">Location</label> <div style="padding-bottom: 15px;" class="row mb-1"> <div class="col-lg-12"> <select class="form-control" id="cmbLocation"> {% for location in locations %} <option value="{{ location.0 }}">{{ location.1 }}</option> {% endfor %} </select> </div> </div> <label class="mb-0" for="cmbCertification">Certification</label> <div style="padding-bottom: 15px;" class="row mb-1"> <div class="col-lg-12"> <select class="form-control" id="cmbCertification"> <option>Lead Prep</option> <option>Greeter</option> <option>Lead Trainer</option> </select> </div> </div> ...... ...... <div id="divAddNewPOC" style="padding-bottom: 10px;padding-left: 2px;"> <button class="btn btn-primary custom-btn" id="btnNewPOC" data-dismiss="modal">Save</button> </div> </fieldset> </form> Here is some JavaScript codes of the poc.js file that is included in the poc_add.html page. $("#btnNewPOC").click(function(){ var selectedLocationVal = $("#cmbLocation").val(); var selectedCertificationVal = $("#cmbCertification").val(); console.log("Location val: " + selectedLocationVal); console.log("Current Objective val: " + selectedCurrentObjVal); console.log("Correct Uniform val: " + selectedCorrectUniformVal); $.post("poc_form_submit",{'location': selectedLocationVal, 'certification': selectedCertificationVal, ...... ...... ...... }, function(data) { ..... ..... ..... }, "html"); }); Here is some part of the urls.py file urlpatterns = [ path('', views.login, name='login'), path('index', views.index, name='index'), .... … -
Form values not updating
I am trying to create a form that will allow users to enter their address, country and other details. This is what i have written in models.py class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) ... class Mentor(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True, related_name='mentor') linkedin = models.URLField(max_length=200,null=True,blank=True) COUNTRIES = ( ('SA', 'South Africa'), ('NG', 'Nigeria'), ('KE', 'Kenya'), ('OT', 'Other') ) address = models.CharField(max_length=500, null=True, blank=True) country = models.CharField(max_length=30, choices=COUNTRIES) invoice_name = models.CharField(max_length=200, null=False, blank=False) account_num = models.IntegerField(max_length=100, null=False, blank=False) bank_name = models.CharField(max_length=50, null=False) branch_code = models.IntegerField(max_length=25, blank=False) forms.py: class MentorPaymentForm(forms.ModelForm): class Meta: model = Mentor fields = ('address', 'country', 'invoice_name', 'account_num', 'bank_name', 'branch_code') views.py: #edit payment details def payment_view(request): user = request.user paymentform = MentorPaymentForm(request.POST, request.FILES, instance= user) if request.method == 'POST': if paymentform.is_valid(): paymentform.save() return HttpResponseRedirect('%s' % (reverse('teachers:billing'))) else: paymentform = MentorPaymentForm(instance= user) return render(request, 'classroom/teachers/app-student-dashboard.html', {'paymentform': paymentform}) and the html form: <div class="form-group"> <label for="name" class="col-md-2 control-label">Name on Invoice</label> <div class="col-md-6"> <div class="form-control-material"> <input type="text" class="form-control used" id="name" value="{{ paymentform.invoice_name }}"> {{ paymentform.invoice_name }} <label for="invoice_name"></label> </div> </div> </div> <div class="form-group"> <label for="address" class="col-md-2 control-label">Address</label> <div class="col-md-6"> <div class="form-control-material"> <textarea class="form-control used" id="address"> </textarea> {{ paymentform.address }} <label for="address">Address</label> </div> </div> I noticed however that the form values are not … -
Issue on django-filter 2.2.0 in python 3.7
Could you please help to me to get rid of this error?searched all over internet but didnt get solution to fix .. Done part : pip install django-filter In setting : i already add 'django_filters', I have filters.py and code inside is : **import django_filters from .models import class OrderFilter(django_filters.FilterSet): class Meta: model = Order fields = ['customer ', 'product', 'date_created']** In views.py : **from .filters import OrderFilter def customer(request,pk): customer = Customer.objects.get(id=pk) orders = customer.order_set.all() total_orders = orders.count() myFilter = OrderFilter() context ={'customer':customer,'orders':orders,'total_orders':total_orders,'myFilter': myFilter } return render(request,'accounts/customer.html',context)** In customer.html : **<form method="get"> {{ myFilter.form }} <button class="btn btn-primary" type="submit">Search</button> </form>** output Error: "'Meta.fields' or 'Meta.exclude' to the %s class." % cls.name AssertionError: Setting 'Meta.model' without either 'Meta.fields' or 'Meta.exclude' has been deprecated since 0.15.0 and is now disallowed. Add an explicit 'Meta.fields' or 'Meta.exclude' to the OrderFilter class. -
mentioning or tagging users or any models in django
Let's say I have a django project of a social network and this site has many users. All the users come from django.contrib.auth.models.User class. Now one user let's say writes a blog and in it, mentions another user with '@' similar to of twitter. So exactly how to do this? What kind of approach should be taken? And coming away from just user model, rather how to do this with any custom model also? Like if I have a Blog model and each blog has a title, how to mention with that title? And most importantly this mentioning should be an automatic thing. Like If one user's name is "PhantomWarrior", then if one writes "@Phant" and he is still writing, it should automatically predict the username "PhantomWarrior" and give the user option to select that for mentioning. Similarly how to do this with the title of a blog? I found this post: how to mention/tag users with '@' on a django developed project in stackoverflow talking about this thing but the answer kind of did not satisfy what I am wanting. So how to do this? Any help will be much appreciated. -
Unique HTML ID Errors Table Forloop
I have a table on my html page that runs a for loop to populate the data. However, I'm getting an error in my Google console that my form fields done have unique ids on them. Im using django crispy form fields. How can i set IDs on this ? {% extends 'base.html' %} {% load crispy_forms_tags %} {% crispy K8Points_ClassroomForm %} {% load static %} {% block content %} <br> <h2> Rapid Fire Mode </h2> <div class= "container"> <div class = "row"> {{form.class_name|as_crispy_field }} {{form.date|as_crispy_field }} {{form.day|as_crispy_field }} {{form.week_of|as_crispy_field }} </div> </div> {% for i in students %} <form action="" method="POST"> <div class = "container" > <div class = "row" > {% csrf_token %} <table style="width:100%" > <tr> <th>ID</th> <th>Name</th> <th>Time Frame</th> <th>Academic</th> <th>Behavior</th> </tr> <tr> <td> {{i.student_name}} </td> <td> {{form.student_name|as_crispy_field }} </td> <td> {{form.time_frame|as_crispy_field }}</td> <td> {{form.academic|as_crispy_field }}</td> <td> {{form.behavior|as_crispy_field }}</td> </form> </tr> {% endfor %} </table> </div> </div> {% endblock %} -
error makemigrations sorl-thumbnail in django
install pillow by pip install pillow install sorl-thumbnail by pip installsorl.thumbnail insert 'sorl.thumbnail', in INSTALLED_APPS on settings file insert {% load thumbnail%} to my(.html) file and insert: {% thumbnail my class.image "100x100" crop="center" as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"> {% endthumbnail %} BUT when python manage.py makemigrations ERROR (my virtualenv) e:\my file\my site\my project>python manage.py showmigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "E:\my file\my site\my virtualenv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "E:\my file\my site\my virtualenv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "E:\my file\my site\my virtualenv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "E:\my file\my site\my virtualenv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "E:\my file\my site\my virtualenv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "E:\my file\my site\my virtualenv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "E:\my file\my site\my virtualenv\lib\site-packages\sorl\thumbnail\models.py", line 2, in <module> from django.utils.encoding … -
Django NoReverseMatch - is not a registered namespace
I am following this tutorial to integrate PayPal into my website. It works perfectly and I am really happy with the concepts I have learned thus far. However, I would also like to integrate a subscription service which is explained in the second tutorial, but I am stuck at this part. First, there is a typo I believe in the 'subscription' function at this line: return render(request, 'ecommerce_app/subscription_form.html', locals() <-- missing closing ')' Second, I get this error: NoReverseMatch at /process_subscription/ 'payment' is not a registered namespace When I navigate to http://localhost:8000/subscribe/ and fire the subscribe button. If anyone is able to figure out what I am missing here or can get this issue fixed for me is highly appreciated :) p.s. I am just a Django beginner. -
How to pass ID (Django ID) or Name from a website page to the django database?
I am making a E-commerce website for selling Books in these website I have different Products and if a customer wish to buy it, he can buy it buy filling their information in the checkout page. I have model name Order which passes all the info like name, email, address, etc. But here how can know for which product the customer is making checkout. class Order(models.Model): order_id = models.AutoField(primary_key=True) item_json = models.CharField(max_length=1000000, default='') name = models.CharField(max_length=1000, default='') email = models.CharField(max_length=1000, default='') address = models.CharField(max_length=1000, default='') city = models.CharField(max_length=1000, default='') state = models.CharField(max_length=1000, default='') zip_code = models.CharField(max_length=1000, default='') Here, I have a field Item_json in which I want that Product name for which customer is making Checkout. Example. If he/she orders a book name Harry Potter. So, in my item_json it should come as item_json. I am making it with Django. Please Help how to do these ??? -
Web-based application to visualize results of data analysis
So, im doing some data analysis using python and PyTorch and i want to develop an app to show the results that is able to run on all kind of devices, so probably something web-based. So far, i only have experience with python. Is using Django and Python a good approach to my problem or should i learn and use something else? -
What should I use for the front-end of my database project?
I just finished writing a program in Python that will automatically watch a folder for some files and when it sees certain files it is adding their data to a MySQL server. I am happy with the way that is working. It uses Python, and Pandas. I am now looking for a way to display, edit, change, add, remove, etc. data from this database but on the front end. I want to set something up that is user friendly to someone who doesn't know how to program, and doesn't know MySQL commands. It doesn't have to be too advanced, but I want to be able to customize and change it to fit my needs. I will be running it locally, through the same MAMP server that is running the MySQL server. I was looking into Django to do this, but I wanted to get some input before taking off. I liked the idea of using Django, because I did the project in Python. But I am not completely attached to sticking with Python, if there is something else that will clearly work great. Any help is appreciated. Thanks! -
Use Django password widget and change password form in user admin site
I am extending the user model in Django and have create a PIN number field that is hashing into the database correctly. However, in the Django admin when viewing a user the pin number field is populated with the hash. Is it possible to use the Django password widget: so that the PIN number field is not populated: and therefore by extension use the template for the change password form to also change the pin? -
Django - Query: how to decode integer field value with its string value 'on the fly'
maybe it is not good practice but I would like to know if it is possible to decode an integer field value with its string value I know I should have a specific models linked as thesaurus... I have a models mymodel I produce a QuerySet mymodel.objects.values('id','var2','var3','var4') for example var3 is an integer (0/1) for Yes/No answer Is it possible to populate my QuerySet with Yes or No instead of its integer value? -
KeyError: 'force_color' error while runing inspectdb in Django
I'm trying to execute inspected command with the exclusion of some tables in Django I've found this question: How do I inspectdb 1 table from database which Contains 1000 tables similar to mine but the problem is when I run the same code i get a strange error script.py from django.core.management.commands.inspectdb import Command from django.conf import settings from SFP_test.settings import DATABASES if not settings.configured: settings.configure() settings.DATABASES = DATABASES Command().execute(table_name_filter=lambda table_name: table_name in ('base_table', 'bp_table', ), database='sfp') error: Traceback (most recent call last): File "/Users/user/PycharmProjects/SFP_crud_test/generateapp.py", line 24, in <module> Command().execute(table_name_filter=lambda table_name: table_name in ('base_table', 'bp_table', ), database='sfp') File "/Users/user/PycharmProjects/SFP_test/venv/lib/python3.7/site-packages/django/core/management/base.py", line 348, in execute if options['force_color'] and options['no_color']: KeyError: 'force_color' -
Rounds a floating-point number inside WITH tag and IF tag
Habitually i use {{ value|floatformat:-2 }} to round numbers and get rid of 0 (ex.: 2.00 = 2). Now inside a WITH tag i got some strange behavior. {% with a.vval_rcov|div:a.vval_100p|mul:100|floatformat:-2 as p1 %} {% with d.vval_rcov|div:d.vval_100p|mul:100|floatformat:-2 as p2 %} {% with p1|sub:p2 as p3 %} <td {% if p3 < 0 %}class="bg-danger" {% elif p3 > 0 %}class="bg-success"{% endif %}>{{ p3 }}%</td> {% endwith %} {% endwith %} {% endwith %} Output for P1 and P2 is ok. Ex.: p1= 51.93, p2 = 51.82 But p3 doesn't display anything! If I remove the |floatformat:-2 on p1 and p2 and adding it to p3 {% with a.vval_rcov|div:a.vval_100p|mul:100 as p1 %} {% with d.vval_rcov|div:d.vval_100p|mul:100 as p2 %} {% with p1|sub:p2|floatformat:-2 as p3 %} <td {% if p3 < 0 %}class="bg-danger" {% elif p3 > 0 %}class="bg-success"{% endif %}>{{ p3 }}%</td> {% endwith %} {% endwith %} {% endwith %} then p3 got a value (0.10) whis is ok but now the {% if %}{% elif %}{% endif %} are strangely not working anymore. And also in that scenario the output of p3 still display trailing zero... Ex.: p1 = 0.002, p2 = 0.003, p3 = -0.001, p3 display -0.00 Any idea … -
Django form not loading
I created a form to save a user's address, city and payment details. However, the html page containing the form is no longer loading and i'm getting this on my terminal from classroom.views import classroom, students, teachers File "C:\Users\User\Documents\GitHub\testingfile\django-multiple-user-types-example-master\django_school\classroom\views\students.py", line 11, i n <module> from ..forms import StudentSignUpForm, TakeQuizForm, StudentUserForm File "C:\Users\User\Documents\GitHub\testingfile\django-multiple-user-types-example-master\django_school\classroom\forms.py", line 96, in <module > not sure what the exact error is. This is what I have in models.py class mentor_payment(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True, related_name= 'mentor_payment') countries = ['South Africa','Nigeria','Kenya','Other'] address = models.CharField(max_length=500, null=True, blank=True) country = models.CharField(max_length=30, choices=countries) invoice_name = models.CharField(max_length=200, null=False,blank=False) account_num = models.IntegerField(max_length=100, null=False,blank=False) bank_name = models.CharField(max_length=50, null=False) branch_code = models.IntegerField(max_length=25, blank=False) forms.py class mentor_payment(forms.Form): countries = ['South Africa','Nigeria','Kenya','Other'] address = forms.CharField(max_length=500) country = forms.ChoiceField(choices=countries) invoice_name = forms.CharField(max_length=200) account_num = forms.IntegerField() bank_name = forms.CharField(max_length=50) branch_code = forms.IntegerField() views.py (teachers): #edit payment details def mentor_payment(request): user = request.user if request.method == 'POST': form = mentor_payment(request.POST, request.FILES, instance= user) if form.is_valid(): form.save() return HttpResponseRedirect('%s' % (reverse('teachers:billing'))) else: form = mentor_payment(instance=user) return render(request, 'classroom/teachers/app-student-dashboard.html',{'payment_form':form}) and the html with the form <form id="edit-payment-details", method="post",enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} <div class="form-group"> {{ payment_form.invoice_name }} <label for="name" class="col-md-2 control-label">Name on Invoice</label> <div class="col-md-6"> <div class="form-control-material"> <input type="text" class="form-control used" id="name" value="{{ … -
Django Channels setting custom channel_name
I'm using Django channels and I'm able to properly connect and send message with builtin channel_name provided. I'm wondering if there is a way to change and register a custom channel_name within web socket connection. I tried changing it but channel_layer alredy stored builtin channel_name and I'm unable to send a message. This is a provided test class class TestWebSocket(AsyncWebsocketConsumer): async def connect(self): self.channel_name = "custom.channelname.UNIQUE" await self.accept() async def test_message(self, event): await self.send(text_data=json.dumps({ 'message': event['message'] })) Here how I send a message: async_to_sync(channel_layer.send)('custom.channelname.UNIQUE', {'type': 'test.message', 'message': 'dfdsdsf'}) I read documentation and it stores channel_name inside db, but each time I perform a connection, that name will change. I want to avoid flooding db with update calls. So this is why I'm trying to force my own channel names. There is a way to change it or is oly waste of time? -
unrecognized url in django
i created a href url for my delete link in my template that takes in an attribute description of a Todo object but the url can't be matched to the one i passed in the path since for some reason i cant call the attribute in my url def todo_delete(request, todo_description): todo = Todo.objects.get(description=todo_description) todo.delete() template = loader.get_template('Todo/index.html') return redirect(template) <div> <h1>{{ TodoDate }}</h1> <p>{{ TodoDescription }}</p> <p class="pubdate">{{ publishDate }}</p> <a href="delete/{{ Todo.description }}">Delete</a> </div> from django.urls import path from . import views app_name = "ToDo" urlpatterns = [ path('', views.index, name='index'), path('details/<todo_description>', views.detail, name='detail'), path('details/delete/<todo_description>', views.todo_delete, name='delete'), path('post', views.todopost, name='post'), ] -
Django returning weird content type [closed]
I have inherited a Django application, which for the most part is working fine. I am rehosting it and in the process noticed that it is throwing up an error in both hosting environments (so it's a Django issue). The issue is the content type: Content-Type: [{'False': False, 'None': None, 'True': True}, {}, {}] Here is the full cURL call: Server: nginx/1.14.0 (Ubuntu) Date: Fri, 17 Jan 2020 14:48:04 GMT Content-Type: [{'False': False, 'None': None, 'True': True}, {}, {}] Content-Length: 45199 Connection: keep-alive Expires: Sat, 18 Jan 2020 01:25:38 GMT X-Frame-Options: SAMEORIGIN Cache-Control: max-age=86400 Does anybody out there know what could cause Django to throw that kind of error? -
How to add buttons in the Django admin interface to update a model field?
I have several markets listed in the admin interface and I'm looking for a solution to populate a market with the price history by clicking on a button in the column (no bulk operation). Populate a market means to enter a list of candlesticks associated to this market as defined by the candle model. What is the best way to do it? Up to now I'm able to create a button in the admin section with django.utils.format_html but I don't know how to link the button to the method exchange.populateMarket(). admin.py @admin.register(Market) class CustomerAdmin(admin.ModelAdmin): list_display = ( 'market', 'populateMarket' ) def populateMarket(self, obj): return html.format_html( '<a class="button" name="print_bnt" href="{}">Populate</a>', 'populate' ) populateMarket.short_description = 'Actions' populateMarket.allow_tags = True models.py # model for markets class Market(models.Model): exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE, related_name='exchange' ) pair = models.CharField(max_length=10) def __str__(self): return self.get_pair_display() # model for candlesticks class Candle(models.Model): market = models.ForeignKey(Market, on_delete=models.CASCADE, related_name='market', null= True ) timestamp = models.DateTimeField(unique=True) volume = models.PositiveIntegerField() op = models.DecimalField(max_digits=20, decimal_places=10, verbose_name='open') hi = models.DecimalField(max_digits=20, decimal_places=10, verbose_name='high') lo = models.DecimalField(max_digits=20, decimal_places=10, verbose_name='low') cl = models.DecimalField(max_digits=20, decimal_places=10, verbose_name='close') def __str__(self): return self.get_timestamp_display() exchange.py def populateMarket(): # download price serie candles = fetchMarket() # create an object for each candle for c … -
502 Bad Gateway error Django password reset in production
My Django site works fine in production,bt when I visit the Django password reset view and submit my email for resetting the password I get a 502 Bad Gateway error.But when in development it works fine.I have did research online ut none seem to solve the issue. I have tried both send grid Google App password but still get th error. Here is my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'someone@gmail.com' EMAIL_HOST_PASSWORD = 'qddoivixifdiu******' EMAIL_PORT = 587 EMAIL_USE_TLS = True database configuration ATABASES = { 'default' : { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME' : 'db', 'USER' : 'myname', 'PASSWORD' : 'kkdnndjdnd', 'PORT' : '5432', 'HOST' : 'localhost', } } -
How to query fields from two related modelforms in a template
What I would like to do is show a table listing all authors, and for each author list their respective books. I'm using a form as some of the fields will be modifiable from the page. models.py class Author(models.Model): author_id = models.CharField(max_length=80, primary_key=True) first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) class Book((models.Model): book_id = models.CharField(primary_key=True) title = models.CharField(max_length=200)A author_id = models.ForeignKey(Author, on_delete=models.CASCADE) forms.py class AuthorForm(forms.ModelForm): class Meta: model = Author fields = '__all__' class BookForm(forms.ModelForm): class Meta: model = Book fields = '__all__' So in the view, I'm passing context which contains the two formsets to the template. views.py if request.method == 'GET': author_dbrecords = Author.objects.all() author_fields = [ f.name for f in Author._meta.get_fields() if not f.is_relation ] authors_detail_list = [{ field:getattr(author, field) for field in author_fields } for author in author_dbrecords ] book_dbrecords = Book.objects.all() book_fields = [ f.name for f in Book._meta.get_fields() if not f.is_relation ] books_detail_list = [{ field:getattr(book, field) for field in book_fields } for book in book_dbrecords ] author_formset = AuthorFormSet(initial=authors_detail_list, prefix='author') book_formset = AuthorFormSet(initial=book_detail_list, prefix='book') context = { 'author_formset':author_formset, 'book_formset':book_formset, } return render(request, 'index.html' context) In the template I can loop through the individual formsets, but I can't work out how to show all book … -
How can I push Django code using dj-database-url, psycopg2 to Heroku?
I am currently building a web project in Django and working on getting the site ready for deployment. I initially deployed the site on Heroku using Sqlite3, with my database code in settings as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } However, due to Heroku's ephemeral file system I realized I needed to switch to Postgres. After following a few different guides I arrived at the following changes to my settings. I first deleted the "DATABASES" as mentioned above and replaced it with the following: import dj_database_url, psycopg2 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': *************, 'USER': **************, 'PASSWORD': ************************************, 'HOST': *********************, 'PORT': '5432', } } db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) When I make these changes everything works perfectly on the local Django development server (127.0.0.1:8000), but once I push the changes through Git and to Heroku I try opening my site on Heroku and get "Application Error" and a suggestion to check my logs. Which report "ModuleNotFoundError: No module named dj_database_url" and similarly any outside library I try to upload to Heroku appears to have this issue. How can I fix this issue and move my site into production? Any help would be … -
Stripe Subscription Events Django
I have setup a basic subscription system using Stripe on my Django Web Application, but I'm confused on how to record the events sent from stripe in my database, would I utilize Django REST API to listen for the events and use that to run a method to correspond with the event. Here's an example, a customer signs up for a subscription and pays in full, the subscription clears stripe and becomes active. One month later, the customers credit card is charged again, but is denied. I read here that Stripe sends two events when this occurs: charge.failed event and an invoice.payment_failed. How would I listen for these events? -
Effect on data on Changing mysql database from 'utf8' to 'utf8mb4' in django live application
I am serving Django application with MySQL back-end with Apache 2. I have configured the database with character-set set to 'utf8' I want to store emojis as well so I need to change the encoding to 'utf8mb4' I just want to know if i change my configuration will will it affect my data? this is my mysql.cnf file [client] database = 'databasename' user = 'username' password = 'password' default-character-set = utf8 This is my django settings for mysql database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': '/path/to/mysql.cnf' } } } What effect will it have on my previously saved data? Also, How shall I do it Should I straight forwardly add the default-character-set = utf8mb4 to my default configuration file.