Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display object info only if model boolean is true
I'm working on a site that allows book submissions/suggestions. Anyone can submit book suggestions via a form on the site. However, I only want to display books on my index.html page that are approved by an admin. I have three boolean options in my models.py: Needs Attention Approved Rejected Needs Attention is checked by default. This lets admins know no one has addressed this submission. Once an admin addresses the submission they can uncheck Needs Attention and then check Approved or Rejected. In my index.html how can I display ONLY submissions that are checked Approved (via the Approved boolean)? -
Multiple user Login where multiple user can login and get redirected to respective pages
I have four types of user like buyer seller organizer and staff. So i would like to know how to implement multiple type login in django -
How to pass context when testing deletion of an instance?
I've got a couple models, Car and CertifyRequest. When a Car instance is created, modified or deleted I need to create a CertifyRequest, which in turn needs to be manually approved. The CertifyRequest instance contains the time it was created. I've tested creating and modifying by injecting context={"now": …} into a CarSerializer instance, but I can't figure out how to do the equivalent when deleting: Delete requests are never passed to the serializer, so I can't access the context in the same way. I can override destroy in the ModelViewSet and use get_serializer_context within it, but I can't seem to pass the serializer to the ModelViewSet instance. I do not want to use a horrible hack like an optional query parameter. -
Cannot access ManyToManyField with through attribute on Django template
Here is a snippet for my ManyToManyField with through attribute models. I'm trying to access a stores's sponsored_stores on Django template, but it doesn't work. I've already tried Store.objects.first().sponsored_stores.all() in Django shell, and it returns a list of sponsored stores. So, I went to Django template to get the sponsored stores on a template file and I tried {{ store.sponsored_stores.all }}, however it returns an empty queryset. Did I put a wrong command on the template level? models.py class Store(TimeStampedModel): sponsored_stores = models.ManyToManyField( 'self', through='Sponsorship', symmetrical=False, related_name='sponsored_store_of_store') class Sponsorship(TimeStampedModel): sponsor_giver = models.ForeignKey(Store, related_name='sponsor_giver', on_delete=models.CASCADE) sponsor_receiver = models.ForeignKey(Store, related_name='sponsor_receiver', on_delete=models.CASCADE) score = models.IntegerField(default=0) class Meta: ordering = ('-score', ) -
Can I take a parameter from the url and use it in a class based view to set field on a form
I am creating a form in my django app. My app has a user, a user can have many transactions and a transaction can have many sales. I'm trying to create a form to add sales to the DB. I'm trying to pass a parameter in the URL (transaction_id) and use it in the Django class-based view CreateView to set the corresponding (foreign key) field in the form. Is it possible to do this and if so how could I apply it. Class based create view below class SaleCreateView(CreateView): model = Sale fields = ['amount_sold', 'total_price_sold', 'note'] def form_valid(self, form): URL below path('sale/new/<int:pk>', SaleCreateView.as_view(), name='sale-create'), Link below {% url 'sale-create' transaction.id %} Sale form below <div> <form method="POST"> {% csrf_token %} <fieldset class ="form-group"> <legend class="border-bottom mb-4">Enter Sale</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class ="btn btn-outline-info" type="submit">Enter</button> </div> </form> </div> -
How do I spot syntax error in urls.py file in Django?
I am upgrading Django 1.11 to Django 2.2. I did all what have to be done. One tiny problem. It says there is a syntax error in urls.py this is urls.py file here: urlpatterns = [ path('', home_page, name='home'), path('about/', about_page, name='about'), path('accounts/login/', RedirectView.as_view(url='/login')), path('accounts/', RedirectView.as_view(url='/account')), path('account/', include("accounts.urls"), # , namespace='account') path('accounts/', include("accounts.passwords.urls")), path('address/', RedirectView.as_view(url='/addresses')), path('addresses/', AddressListView.as_view(), name='addresses'), path('addresses/create/', AddressCreateView.as_view(), name='address-create'), path('addresses/(?P<pk>\d+)/', AddressUpdateView.as_view(), name='address-update'), path('analytics/sales/', SalesView.as_view(), name='sales-analytics'), path('analytics/sales/data/', SalesAjaxView.as_view(), name='sales-analytics-data'), path('contact/', contact_page, name='contact'), path('login/', LoginView.as_view(), name='login'), path('checkout/address/create/', checkout_address_create_view, name='checkout_address_create'), path('checkout/address/reuse/', checkout_address_reuse_view, name='checkout_address_reuse'), path('register/guest/', GuestRegisterView.as_view(), name='guest_register'), path('logout/', LogoutView.as_view(), name='logout'), path('api/cart/', cart_detail_api_view, name='api-cart'), path('cart/', include("carts.urls"), path('billing/payment-method/', payment_method_view, name='billing-payment-method'), path(r'billing/payment-method/create/', payment_method_createview, name='billing-payment-method-endpoint'), path('register/', RegisterView.as_view(), name='register'), path('bootstrap/', TemplateView.as_view(template_name='bootstrap/example.html')), path('library/', LibraryView.as_view(), name='library'), path('orders/', include("orders.urls"), # , namespace='orders') path('products/', include("products.urls"), # , namespace='products') path('search/', include("search.urls"), # , namespace='search') path('settings/', RedirectView.as_view(url='/account')), path('settings/email/', MarketingPreferenceUpdateView.as_view(), name='marketing-pref'), path('webhooks/mailchimp/', MailchimpWebhookView.as_view(), name='webhooks-mailchimp'), path('admin/', admin.site.urls) ] This is the snytax error thrown here. I think I did everything right, still I don't have any clue what is going on wrong here. > File > "c:\Users\Administrator\Desktop\eCommerce-master\src\ecommerce\urls.py", > line 82 > ] > ^ SyntaxError: invalid syntax Please kindly help me thank you in advancefor your help -
How do I insert a javascript variable into a model in Django?
I'm trying to save the longitude and latitude of a user to a model to use with various API's for things like traffic and weather and what not. I get the users latitude and longitude by using the navigator.geolocation that is in html5. What is the best way to save this info to a UserProfile model? I've tried setting up a form to use but can't get anything to work with the check box I have that enables geolocation. I've also thought of using ajax but don't know how to pass the data to the model in django. <script type="text/javascript"> $(document).ready(function(){ $('input[type="checkbox"]').click(function(){ if($(this).prop("checked") == true){ getLocation() } else if($(this).prop("checked") == false){ console.log("Location services are disabled"); } }); }); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { console.log("Geolocation is not supported by this browser."); } } function showPosition(position) { console.log("Latitude: " + position.coords.latitude + " Longitude: " + position.coords.longitude); var latlon = (position.coords.latitude + ','+ position.coords.longitude) console.log(latlon) }; This is what I'm using to get the location of the user, it's in a profile.html page I have set up for the user. I'm new to Django and coding in general as well as stackoverflow, so if I need to … -
server error please contact the administrator
enter image description herethis is my contact views.py and i can't submit a contact since it gives me server error please contact the admin in browser. Blockquote aV.jpg -
How to access through model in django
I'm trying to manage sponsored stores of each store. There is sponsored_stores field in Store model and it has through attribute to connect the field to Sponsorship model. I need it to be done since I need score field between a sponsor store and a sponsored store. models.py class Store(models.Model): sponsored_stores = models.ManyToManyField( 'self', related_name='sponsored_stores_of_store', blank=True, through='Sponsorship', symmetrical=False) class Sponsorship(TimeStampedModel): sponsor_giver = models.ForeignKey(Store, related_name='sponsor_giver', on_delete=models.CASCADE) sponsor_receiver = models.ForeignKey(Store, related_name='sponsor_receiver', on_delete=models.CASCADE) score = models.IntegerField(default=0) I'm trying to access score field through sponsored_stores, so I tried something like store.sponsored_stores.sponsorship.score. I know it's not working, but I can't figure out how I can access score field from sposored_stores. -
Handle POST request query param from browsable API in Django Rest Framework
I have a requirement of having a query param in a POST request with the JSON payload in the body. Now in django-rest-framework I have been able to do that by overriding the perform_create method of ModelViewSet in my view class, but what I can do to have it appear in browsable API. I tried django-filter and its backend but they are geared towards filtering(obviously) in a GET request. I don't want to filter but want to just use that query param as a parameter to run celery tasks during perform_create. This is how my viewset looks right now. Don't worry about the run_flow method its selinon thing that I am using, it will run celery tasks based on my flow. class AbcViewSet(viewsets.ModelViewSet): queryset = Abc.objects.all() serializer_class = AbcSerializer filterset_fields = ('fk_field', ) def perform_create(self, serializer): query_param1 = self.kwargs.get(self.request.query_params.get('param', None)) ...schedule salary using the query_param1 and save the model... my request for this will be like http://127.0.0.1:8000/abc/?param=xyz If you notice above I want to be able to fill thatparam using browsable API. Trying to search I have a feeling it will involve creating some kind of HTML view rendering for the param but If its more easier available from browsable … -
ValueError: invalid literal for int() with base 10: '20:00:00'
I have exported csv files from the database and would like to store the csv information in my django models. I am receiving the ValueError problem. models.py class Act(models.Model): Name = models.CharField(max_length=100) Stage = models.CharField(max_length=100) Start_Time = models.TimeField() End_Time = models.TimeField() Date = models.DateField() def __str__(self): return self.name load_act_data.py import csv from datetime import time from polls.models import Act with open('../data/csv/Acts.csv') as f: reader = csv.reader(f) for row in reader: acts = Act(row[0],row[1],int(row[2]),int(row[3],row[4])) acts.save() Traceback Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\tawhi\project\2019-ca472-John-Tawhid\festimaps\polls\load_act_data.py", line 8, in <module> acts = Act(row[0],row[1],int(row[2]),int(row[3],row[4])) ValueError: invalid literal for int() with base 10: '20:00:00' -
How to filter "Inline model" objects according to the parent foreign key value
I am new in Django. I am having troubles to filter inline model objects according to their parent field value. I have two Models Progarm and Class . I want that classes in Program Inline Which have same department to parent's department Here are my models: class Program(models.Model): Name = models.CharField("Program Name", max_length=20) DepartmentId = models.ForeignKey(Department, on_delete=models.CASCADE) def __str__(self): return self.Name class Class(models.Model): Name = models.CharField(max_length=20) DepartmentId = models.ForeignKey(Department, on_delete=models.CASCADE) ProgramId = models.ForeignKey(Program, on_delete=models.CASCADE) def __str__(self): return self.Name Now admin class myProgramAdmin(admin.ModelAdmin): inlines = [ClassInline] class ClassInline(admin.StackedInline): model = Class extra = 0 how can i get that classes which have same department to parent department. Please Give some advise. Thanks in advance -
Is it even possible what I'm trying to do with Django?
I'm setting up a Heroku site to deploy a Django app for a school project. The problem is with static files using whitenoise in Django. Quick context: My app consists of a form that takes 4 values that I use for quick math calculation inside a script. The aim of this script is to perform the calculations, draw a plot using matplotlib and save it in the static folder of my django app replacing the old one if it already exists. This static file is used to display in a html page on the site. Locally It works like a charm updating the plot each time I submit a new form. But when I try on Heroku it throws an "[Errno 2] No such file or directory: '/Users/jeff/Desktop/trydjango/src/static/yield_curve.png'" when I submit the form. Here's the settings.py I have concerning static files: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' My directory look like this : src |-- /TER |-- -- /settings.py |-- /graph |-- /static/... |-- /staticfiles/... |-- /manage.py I would like for my site to refresh the image each time I submit a form using the new 'yield_curve.png' I saved in the static … -
Heroku app successfully deploying, but receiving application error when loading site
My logs don't indicate any errors as far as I can tell, but I'm receiving the following error when loading the site: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail Below you can find the logs. Am I missing something here? -----> Python app detected -----> Uninstalling stale dependencies Uninstalling Django-2.1.5: Successfully uninstalled Django-2.1.5 Uninstalling Pillow-5.4.1: Successfully uninstalled Pillow-5.4.1 -----> Installing requirements with pip Collecting dj-database-url==0.5.0 (from -r /tmp/build_99fe21a8dcc00005ce600053adc20260/requirements.txt (line 1)) Downloading https://files.pythonhosted.org/packages/d4/a6/4b8578c1848690d0c307c7c0596af2077536c9ef2a04d42b00fabaa7e49d/dj_database_url-0.5.0-py2.py3-none-any.whl Collecting Django==2.1.5 (from -r /tmp/build_99fe21a8dcc00005ce600053adc20260/requirements.txt (line 2)) Downloading https://files.pythonhosted.org/packages/36/50/078a42b4e9bedb94efd3e0278c0eb71650ed9672cdc91bd5542953bec17f/Django-2.1.5-py3-none-any.whl (7.3MB) Collecting django-heroku==0.3.1 (from -r /tmp/build_99fe21a8dcc00005ce600053adc20260/requirements.txt (line 3)) Downloading https://files.pythonhosted.org/packages/59/af/5475a876c5addd5a3494db47d9f7be93cc14d3a7603542b194572791b6c6/django_heroku-0.3.1-py2.py3-none-any.whl Collecting gunicorn==19.9.0 (from -r /tmp/build_99fe21a8dcc00005ce600053adc20260/requirements.txt (line 4)) Downloading https://files.pythonhosted.org/packages/8c/da/b8dd8deb741bff556db53902d4706774c8e1e67265f69528c14c003644e6/gunicorn-19.9.0-py2.py3-none-any.whl (112kB) Collecting Pillow==5.4.1 (from -r /tmp/build_99fe21a8dcc00005ce600053adc20260/requirements.txt (line 5)) Downloading https://files.pythonhosted.org/packages/ae/2a/0a0ab2833e5270664fb5fae590717f867ac6319b124160c09f1d3291de28/Pillow-5.4.1-cp37-cp37m-manylinux1_x86_64.whl (2.0MB) Collecting psycopg2==2.8.2 (from -r /tmp/build_99fe21a8dcc00005ce600053adc20260/requirements.txt (line 6)) Downloading https://files.pythonhosted.org/packages/23/7e/93c325482c328619870b6cd09370f6dbe1148283daca65115cd63642e60f/psycopg2-2.8.2.tar.gz (368kB) Collecting whitenoise==4.1.2 (from -r /tmp/build_99fe21a8dcc00005ce600053adc20260/requirements.txt (line 8)) Downloading https://files.pythonhosted.org/packages/fd/2a/b51377ab9826f0551da19951257d2434f46329cd6cfdf9592ea9ca5f6034/whitenoise-4.1.2-py2.py3-none-any.whl Installing collected packages: dj-database-url, Django, whitenoise, psycopg2, django-heroku, gunicorn, Pillow Running setup.py install for psycopg2: started Running setup.py install for psycopg2: finished with status 'done' Successfully installed Django-2.1.5 Pillow-5.4.1 dj-database-url-0.5.0 django-heroku-0.3.1 gunicorn-19.9.0 psycopg2-2.8.2 whitenoise-4.1.2 -----> $ python manage.py collectstatic … -
clean(self) method is not called when if form.is_valid()
I have a RegisterUserForm that is bound to a CustomUser (that extends AbstractUser). Before I save the user, I want to check password1 and password2 if they are equal but the clean(self) method is not called. the user is created even if the passwords are not the same. I have read a lot of questions and tried a lot of things but couldn't find an answer. My code is below I tried adding an init and a save method but still does not work. class RegisterUserForm(forms.ModelForm): password1=forms.CharField(label=_("password"), min_length=4) password2=forms.CharField(label=_("repeat password"), min_length=4) class Meta: model = CustomUser fields = ('first_name', 'last_name', 'email', 'password1','password2') def save(self, *args, **kwargs): self.full_clean() return super().save(*args, **kwargs) def clean(self): cleaned_data = super().clean() print("clean is called") password1 = form.cleaned_data.get("password1") password2 = form.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise ValidationError('password_mismatch') return self.cleaned_data and my view is def register(request): if request.method=='POST': form = RegisterUserForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.set_password(form.cleaned_data['password1']) user.save() email = user.email messages.success(request, f'user with {email} created successfully') return redirect('home') else: form = RegisterUserForm() return render(request, 'users/register.html', {'form':form }) -
I am appending rows to a table and populating with data from an API using javascript, can I get table to refresh the rows every minute
I am trying to create rows that refresh every minute, I have created the table in html and am adding rows to it via javascript. is there a way i can get these rows to refresh every minute without appending more rows to the bottom of the table Table in my .html file below <table class="table table-dark" id = "statsTable"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Symbol</th> <th scope="col">Price </th> <th scope="col">Day High</th> <th scope="col">Day Low</th> <th scope="col">Market Cap</th> <th scope="col">%24h</th> </tr> </thead> <tbody id = "stats"> </tbody> </table> javascript below {% block jquery %} var endpoint = '/api/table/data' populateTable() function populateTable(){ $.ajax({ method: "GET", url: endpoint, success: function(data){ console.log(data) var table_data =''; for (var key in data){ table_data += '<tr>'; table_data += '<td><a href = "{% url 'webapp-graph'%}"><img src="https://www.cryptocompare.com'+data[key].EUR.IMAGEURL+'"alt="'+key+'logo" style =" width:3em; height:auto;"></a></td>'; table_data += '<td>' +key+ '</td>' table_data += '<td>' +data[key].EUR.PRICE+ '</td>'; table_data += '<td>' +data[key].EUR.HIGHDAY+ '</td>'; table_data += '<td>' +data[key].EUR.LOWDAY+ '</td>'; table_data += '<td>' +data[key].EUR.MKTCAP+ '</td>'; if (data[key].EUR.CHANGEPCT24HOUR[0] == '-') { table_data += '<td style = "color:red">' +data[key].EUR.CHANGEPCT24HOUR+ '</td>'; } else { table_data += '<td style = "color:green">' +data[key].EUR.CHANGEPCT24HOUR+ '</td>'; } table_data += '</tr>'; } $('#stats').append(table_data); }, }) } {% endblock %} -
return int(value) ValueError: invalid literal for int() with base 10: 'Umi Falafel'
I have exported csv files from the database and would like to store the csv information in my django models. I am receiving the ValueError problem. I have tried converting the string to an integer within my .py files load_vendor_data.py import csv from polls.models import Vendors with open('../data/csv/Vendors.csv') as cap: reader = csv.reader(cap) # i = 0 for row in reader: vendors = Vendors(row[0],row[1],row[2]) vendors.save() # i = i + 1 models.py class Vendors(models.Model): name = models.CharField(max_length=100) location = models.CharField(max_length=100) price_range = models.CharField(max_length=100) def __str__(self): return self.name class Act(models.Model): Name = models.CharField(max_length=100) Stage = models.CharField(max_length=100) Start_Time = models.TimeField() End_Time = models.TimeField() Date = models.DateField() def __str__(self): return self.name Stacktrace Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\tawhi\project\2019-ca472-John-Tawhid\festimaps\polls\load_vendor_data.py", line 9, in <module> vendors.save() File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\base.py", line 904, in _save_table forced_update) File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\base.py", line 934, in _do_update filtered = base_qs.filter(pk=pk_val) File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\query.py", line 784, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\query.py", line 802, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\sql\query.py", line 1250, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\tawhi\project\cfehome\lib\site-packages\django\db\models\sql\query.py", line 1276, in _add_q … -
Django.core.exceptions.ImproperlyConfigured error when deploying to Heroku
When trying to deploy my django app to Heroku, I'm receiving the following error in the logs: -----> Python app detected Skipping installation, as Pipfile.lock hasn't changed since last deploy. -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 343, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 249, in delete_file if self.storage.exists(prefixed_path): File "/app/.heroku/python/lib/python3.7/site-packages/django/core/files/storage.py", line 308, in exists return os.path.exists(self.path(name)) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/storage.py", line 43, in path raise ImproperlyConfigured("You're using the staticfiles app " django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! Push rejected, failed to compile Python app. … -
Django Oracle Insertion
My Environment: Redhat 7 Oracle 12.c Django 2.1 cx_Oracle 7.1.2 When I tried to insert or create or do python manage.py makemigrations or python manage.py migrate I get the error : 'The database did not return a new row id. Probably "ORA-1403: ' django.db.utils.DatabaseError: The database did not return a new row id. Probably "ORA-1403: no data found" was raised internally but was hidden by the Oracle OCI library (see https://code.djangoproject.com/ticket/28859). Can someone please tell me how to fix the problem Im going crazy here -
Problems to use bootstrap datePicker in Django templates
im coding a very simple site and I need to use DatePicker's bootstrap in my home page. Here u can find my rep on github. So I have this two models: class State(models.Model): initials = models.CharField('Sigla', max_length=2, blank = False) name = models.CharField('Estado', max_length=50, blank = False) count = models.IntegerField('Total de Eventos', default=0) def __str__(self): return self.name class Meta: verbose_name = 'Estado' verbose_name_plural = 'Estados' ordering = ['initials'] class Alien(models.Model): city = models.CharField('Cidade', max_length=50, blank = False) state = models.ForeignKey(State, verbose_name='Estado', related_name='state_fk', on_delete=models.DO_NOTHING) date = models.DateField('Data', blank = False, default = date.today) # ON_DELETE SETADO COMO DO_NOTHING POIS NENHUM ESTADO # SERÁ DELETADO DO DB EM NENHUM MOMENTO. @property def state_initial(self): return self.state.initials @property def state_name(self): return self.state def save(self, *args, **kwargs): if self.pk is None: self.state.count += 1 self.state.save() super(Alien, self).save(*args, **kwargs) pass def __str__(self): return self.city class Meta: verbose_name = 'Ocorrência' verbose_name_plural = 'Ocorrências' For this two I created this form: from django import forms from django.conf import settings from .models import Alien, State class AlienForm(forms.ModelForm): class Meta: model = Alien fields = ['city', 'state', 'date'] widgets = {'date': forms.DateInput(attrs={'class': 'datepicker'})} and this home page template: {% extends "base.html" %} {% load static %} {% block date_script %} … -
Understanding Django Versions on Ubuntu
I am developing a web-app using Digital Oceans "one-click Django droplet". I noticed I am getting some error messages because I wrote the original code locally on my PC using Python 3.6 and Django 2.2. On the Console when I type python -m django --version it returns 1.11.20 However, when I type python3 -m django --version it returns 2.2. So my question is: How do I ensure that my django app is running on python 3 and Django 2.2? Do I have to start gunicorn differently? In case readers haven't used Digital Oceans "one-click Django droplet" : It utilizes gunicorn, NGINX, and ubuntu. Thank you! ` -
How can I pass a Value from a Django template to a View
I need to pass a DateRange from a template to a view, so the Graph can be filtered by that Range, but I can not get the DateRange Value. I am Working with Django 2, and i have a while trying to solve this issue. Can somebody give a hint??? <div class="card-header"> <form class="form-group mb-xl-0 float-right" method="get"> <button id="send" name="button" >send</button> <div id="reportrange" class="overflow-hidden form-control" name="ref_date2"> <input class="far fa-calendar" name="ref_date"> <span></span> <i class="fas fa-caret-down" name="ref_date3"></i> </div> </form> <h5 class="card-title">Eficiencia por Rango de Horas</h5> </div> <script> var send = document.getElementById("send"); send.addEventListener("click", function() { var startDate = $('#reportrange').data('daterangepicker').startDate; var content = encodeURIComponent(document.getElementByName("ref_date").value); var endDate = "HOLA"; } function myFunction() { var d = 100 console.log(d); } </script> <script> document.addEventListener("DOMContentLoaded", function(event) { var start = moment().subtract(29, 'days'); var end = moment(); function cb(start, end) { $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); } $('#reportrange').daterangepicker({ startDate: start, endDate: end, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] } }, cb); cb(start, end); }); </script> View: Python class RevPashPageView(TemplateView): template_name = "softrest/revPash.html" def get(self, request, *args, … -
Error when sending email through Sendgrid API
On my production server I am getting the error below "init() got an unexpected keyword argument 'apikey'" The same code on the development server is working. My production server is running gunicorn and I have added the environment variable SENDGRID_API_KEY to the gunicorn.service file. I have restarted gunicorn and nginx. I can see that the environment variable is loaded. My production server is running gunicorn and I have added the environment variable SENDGRID_API_KEY to the gunicorn.service file. I have restarted gunicorn and nginx. I can see that the environment variable is loaded. The method I am calling to send the email is below: def sendtestemail(to): sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) from_email = Email("<myemail>@<mydomain>.com") to_email = Email(to) subject = "Sending with SendGrid is Fun" content = Content("text/plain", "and easy to do anywhere, even with Python") mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) return [response.status_code, response.body, response.headers] -
Django Tutorial Part 1: incorrect path causing (404)
I have setup part 1 of the django tutorial and am receiving the following error when trying to access the polls app:[HTTP Error Message] I'm using Django 2.2, Python 3.7, Apache 2.4.6, mod-wsgi 4.6.5. I was able to complete the tutorial using the built in web server, but I started running into problems when I added Apache and mod-wsgi into the mix. Here is my code: proto/urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] polls/urls.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") The only thing changed in the settings.py was the TIMEZONE. Everything else is set to defaults. Something seems to be up with the urls and path matching. The url I used (proto.slc.venturedata.com/polls/) should match the 'polls/' path, but the error message says that the path is empty. In experimenting I found that I didn't receive an error if I modified proto/urls.py by replacing the 'polls/' path with an empty path: ''. urlpatterns = [ path('', include('polls.urls')), path('admin/', admin.site.urls), ] Am I missing something? -
(nginx + gunicorn) small server instance drops/timeouts connections on +60 simple API requests / second. Can it be improved?
I'm setting up the first production architecture for my Django-based app. I'm using nginx + gunicorn + remote postgres database setup. After performing simple API load tests with https://loader.io I've found out that when increasing the number of clients sending api requests over 60 clients/second for 30 seconds-long test the tool shows errors that the connections timeout. When using double server setup with a load balancer I can double the clients/second number but I would expect a single 3vCPU /1 GB ram setup to be able to handle more than 30 requests/second - am I right? I've tried a lot of differente gunicorn / nginx config parameters but nothing seems to help. This is the content of my /etc/nginx/nginx.conf file: user www-data; worker_processes auto; pid /run/nginx.pid; worker_rlimit_nofile 100000; events { worker_connections 4000; multi_accept on; use epoll; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; server_names_hash_bucket_size 512; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; gzip_vary on; gzip_types text/plain text/css application/json …