Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Clear entire cart with one button click - Django/Python
So I have a working shopping cart. You can add and delete items, one at a time. However, once payment is submitted, I want to be able to just click a button and delete all of the items in the cart at once. Here is what I have: Cart Views.py: def remove_from_cart(request, id): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: return HttpResponseRedirect(reverse("cart")) cartitem = CartItem.objects.get(id=id) cartitem.delete() return HttpResponseRedirect(reverse("cart")) try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: return HttpResponseRedirect(reverse("cart")) cartitem = Cart.objects.all() cartitem.delete.all() return HttpResponseRedirect(reverse("cart")) The top section is what allows users to delete one item at a time. The second half is me attempting to use the same view on the same page to delete every cart item. Models.py: class CartItem(models.Model): cart = models.ForeignKey('Cart', null= True, blank = True, on_delete = models.CASCADE) product = models.ForeignKey(Product, on_delete = models.CASCADE) quantity = models.IntegerField(default=1) line_total = models.DecimalField(default = 10.99, max_digits = 1000, decimal_places=2) def __unicode__(self): try: return str(self.cart.id) except: return self.product.title class Cart(models.Model): total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) active = models.BooleanField(default=True) def __unicode__(self): return "Cart id: %s" %(self.id) Urls.py: url(r'^add-to-cart/(?P<item_id>[-\w]+)/$', add_to_cart, name="add_to_cart"), url(r'^cart/(?P<id>\d+)/$', carts_views.remove_from_cart, name='remove_from_cart'), url(r'^cart/(?P<slug>[\w-]+)/(?P<qty>\d+)/$', carts_views.update_cart, name='update_cart'), url(r'^cart/$', carts_views.view, name='cart'), url(r'^cart/(?P<id>\d+)/$', carts_views.remove_from_cart, name='clear_cart'), HTML: {% for item in cart.cartitem_set.all %} <a … -
e.preventDefault() not letting me submit my form
I wrote some javascript to validate a form. However, if the form fields pass all validations, the form never submits! Is my code somehow incorrectly preventing the form from being able to submit? If I delete all of the javascript and use browser's built-in validation then form executes fine and user is added to the database. const form = document.getElementById('form'); const first_name = document.getElementById('first_name'); const last_name = document.getElementById('last_name'); const username = document.getElementById('username'); const email = document.getElementById('email'); const password = document.getElementById('password'); const password2 = document.getElementById('password2'); // Show input error message function showError(input, message) { input.className = 'form-control is-invalid'; const small = input.parentElement.querySelector('small'); small.className = 'invalid-feedback'; small.innerText = message; } // Show success outline function showSuccess(input, message) { input.className = 'form-control is-valid'; const small = input.parentElement.querySelector('small'); small.className = 'valid-feedback'; small.innerText = message; } function checkRequired(inputArray) { inputArray.forEach(function(input) { if (input.value.trim() === '') { showError(input, `${getFieldName(input)} is required`); return false; } else { showSuccess(input, "Looks Good!"); return true; } }); } // Check email is valid function checkEmail(input) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if (re.test(input.value.trim())) { showSuccess(input, 'Looks Good!'); return true; } else { showError(input, 'Email is not valid'); return false; } } // Check input length function checkLength(input, min, max) { if … -
Book value calculation in Django
quick question. I have the following model: class Shares(models.Model): name = models.CharField(max_length=128) ticker = models.CharField(max_length=128) date = models.DateField() quantity = models.FloatField(default=0) price = models.FloatField(default=0) currency = models.CharField(max_length=128) and I'm trying to calculate the book value of each position with the following view: class SharesListView(ListView): model = Shares context_object_name = 'shares_details' def get_context_data(self, **kwargs): context = super(SharesListView, self).get_context_data(**kwargs) latest_fx = fx_table.objects.last() queryset = context['shares_details'].annotate(book_value=Case( When(quantity > 0, then=F('price')*('quantity')), default= Value (0), output_field=FloatField() ) ) context['shares_details'] = queryset context['total'] = queryset.aggregate(sum=Sum('book_value'))['sum'] return context However I can't make it work. Would you please be able to help? Thanks in advance -
In wagtail how do I setup the v2 api to attach the full base url ( e.g. http://localhost:8000" ) to steamfield images and richtext embeds?
I am currently using nuxt.js as a frontend for my wagtail headless cms. When I load a richtext field or an image block within a streamfield I am unable, or don't know how to, attach the full base url of the wagtail server so when it gets rendered on the nuxtjs site it resolves to src="/media/images/image.png which in the end tries to find the image on the nuxtjs site http://localhost:3000 and it needs to find it on the wagtail server side http://localhost:8000. For standard images I can intercept and prepend the server base url, but not when it comes to anything inside a streamfield. -
Postgresql trigger fire for arrayfield on tsvector
We have the following model which creates a Trigger event for simple TextField on INSERT or UPDATE. from django.db import models from django.contrib.postgres.search import SearchVectorField from django.contrib.postgres.indexes import GinIndex class Page(models.Model): title = models.CharField(max_length=100, unique=True) content = models.TextField() # New modifications. A field and an index content_search = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["content_search"])] Custom migration file to create trigger event for postgres database. from django.db import migrations class Migration(migrations.Migration): dependencies = [ # NOTE: The previous migration probably looks different for you, so # modify this. ('web', '0002_auto_20190524_0957'), ] migration = ''' CREATE TRIGGER content_search_update BEFORE INSERT OR UPDATE ON web_page FOR EACH ROW EXECUTE FUNCTION tsvector_update_trigger(content_search, 'pg_catalog.english', content); -- Force triggers to run and populate the text_search column. UPDATE web_page set ID = ID; ''' reverse_migration = ''' DROP TRIGGER content_search ON web_page; ''' operations = [ migrations.RunSQL(migration, reverse_migration) ] How to create a trigger event in the migration file for Arrayfield as tsvector_update_trigger expects text or varchar field.?? class Page(models.Model): title = models.CharField(max_length=100, unique=True) content = models.TextField() tags = ArrayField(models.TextField(blank=True),blank=True,null=True,default=list) ### ['wordpress','drupal'] content_search = SearchVectorField(null=True) tags_search = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["content_search","tags_search"]),] -
I would like to be able to redirect connected users to the main page and also use user_passes_test and login_required thank you
I created a user_passes_test (groups) to limit users according to user groups but when I redirect all the users already connected to the main page it creates a redirection loop and firefox displays 'The page is not redirected correctly' is the link to my home page is the link that is accessible to all connected users [is the page link which authorize when i want to leave d home page to this page with a user who is not authorized firefox referral The page is not redirected correctly Firefox has detected that the server is redirecting the request for this address in a way that will not be successful. {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="{% static 'accounts/img/favicon.ico' %}"> <title>Authentification</title> <link href="{% static 'accounts/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'accounts/css/loguer.css' %}" rel="stylesheet"> <script type="text/javascript" src="{% static 'accounts/js/jquery-3.3.1.min.js' %}"></script> <script type="text/javascript" src="{% static 'accounts/js/bootstrap.min.js' %}"></script> </head> <body> <div class="container-fluid"> <div class="row"> <main role="main" class="col-sm-6 ml-sm-auto col-md-12 pt-6"> <div class="container"> <div class="card card-container"> <!-- <img class="profile-img-card" src="//lh3.googleusercontent.com/-6V8xOA6M7BA/AAAAAAAAAAI/AAAAAAAAAAA/rzlHcD0KYwo/photo.jpg?sz=120" alt="" /> --> <img class="profile-img-card" src="{% static 'accounts/img/academy.png' %}" /> {% if form.errors or error %} <p … -
Django rest frame work nested serializer doesn't update object
I have a model with a Foreign Key field and upon serialization of the object, I'm performing a create method on it which updates the field if it None. In the second serializer, I overwrote the update method to make sure that the data was inserted. I don't get any errors when running the update, yet, the field is not updated. models: class Mission(models.Model): # Some other irrelevant fields. area = models.CharField( name='Area', max_length=8, choices=AREAS, ) date_added = models.DateTimeField(verbose_name="Date Added", default=now()) gdt = models.ForeignKey(KnownLocation, on_delete=models.PROTECT) class KnownLocation(models.Model): """ Add known location to map, But also use this as Base Object to describe locations as GDTs. :rtype Django base model for GeoLocation. """ name = models.CharField(name="Name", unique=False, primary_key=True, max_length=150, blank=False, help_text="Enter the location's name") area = models.CharField(name='Area', max_length=8, choices=AREAS, ) date_added = models.DateTimeField(default=timezone.now) latitude = models.FloatField(name="Latitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=DEFAULT_VALUE) longitude = models.FloatField(name="Longitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", default=DEFAULT_VALUE) elevation = models.FloatField(name="elevation", help_text="Enter the location's ~Sea Level~ elevation, or Leave empty for auto-fill. ", blank=True, null=True, verbose_name="Elevation" ) serializers: class KnownLocationSerializer(HyperlinkedModelSerializer): def create(self, validated_data): """ Checks if user inputted the elevation or left … -
Postgresql fire TRIGGER on BEFORE INSERT OR UPDATE on multiple columns in single query
from django.db import models from django.contrib.postgres.search import SearchVectorField from django.contrib.postgres.indexes import GinIndex class Page(models.Model): title = models.CharField(max_length=100, unique=True) content = models.TextField() # New modifications. A field and an index content_search = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["content_search"])] Custom migration file to create trigger event for postgres database. from django.db import migrations class Migration(migrations.Migration): dependencies = [ # NOTE: The previous migration probably looks different for you, so # modify this. ('web', '0002_auto_20190524_0957'), ] migration = ''' CREATE TRIGGER content_search_update BEFORE INSERT OR UPDATE ON web_page FOR EACH ROW EXECUTE FUNCTION tsvector_update_trigger(content_search, 'pg_catalog.english', content); -- Force triggers to run and populate the text_search column. UPDATE web_page set ID = ID; ''' reverse_migration = ''' DROP TRIGGER content_search ON web_page; ''' operations = [ migrations.RunSQL(migration, reverse_migration) ] Trigger which works for only one column field content_search whenever Page table get's updated. How do I create a trigger event for both following multiple columns in single fire class Page(models.Model): title = models.CharField(max_length=100, unique=True) content = models.TextField() content_search = SearchVectorField(null=True) title_search = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["content_search","title_search"]),] -
Getting the correct data for the form in Django
Currently, I am getting the data from the whole database so I am attempting to filter it and then pass the filtered model to the form so only the data relevant to the user is shown. I did it according to what I found on google but I am getting this error: too many values to unpack (expected 2) It makes no sense to me as I am filtering the data as expected. Here is my code: models: from django.db import models from django.contrib.auth.models import User from posts.models import PDF from children.models import Children HEADER_CHOICES = [ ('Financial Support', 'Financial Support'), ('Educational Support', 'Educational Support'), ('Governmental Support', 'Governmental Support '), ('Charity Support Groups', 'Charity Support Groups'), ('Therapy Support', 'Therapy Support '), ('Transport Support', 'Transport Support ') ] AGE_CHOICES = [ ('0-4', '0-4'), ('4-11', '4-11'), ('11-18', '11-18'), ('18-25', '18-25') ] class Timeline(models.Model): header = models.CharField(max_length=30, choices=HEADER_CHOICES) age = models.CharField(max_length=6, choices=AGE_CHOICES) child = models.ForeignKey(Children, on_delete=models.CASCADE) class Pdf(models.Model): pdf = models.FileField(upload_to='timelinepdfs') timeline = models.ForeignKey(Timeline, on_delete=models.CASCADE) children model: from django.db import models from django.contrib.auth.models import User from PIL import Image from django.urls import reverse from django.dispatch import receiver from django.db.models import signals DIAGNOSIS_CHOICES = [ (1, ("Yes")), (2, ("No")) ] class Children(models.Model): first_name = … -
Server-side implementation of image downloading in Django web app (images served from a remote location)
I'm trying to do a server side implementation of a download button for static assets (served via AWS S3) in a Django web app. What I've tried: I first tried the download attribute with a tags. But it doesn't cover Firefox in my experience (i.e. instead of the asset being downloaded, a new browser tab opens and the asset renders in that window). I tried a server-side solution once the aforementioned failed. Specifically, in an html template, I've got: <form method="GET" action="{% url 'download_image' %}" target="_blank"> <input type="hidden" name="img_url" value="{{ img_url }}"> <button>Download</button> </form> And in a view, I'm trying: def download_image(request): """ Download the image """ image_url = request.GET.get("img_url",None) # image_url value is //s3.eu-central-1.amazonaws.com/my-app/ebc4596f-d7db-340f-b7d6-4952c949f011.jpg if image_url: with open('https:'+image_url, 'rb') as fh: response = HttpResponse(fh.read(), content_type="image/jpg") response["Content-Disposition"] = 'attachment; filename="content.jpg"' return response This results in an IOError: No such file or directory: u'https://s3.eu-central-1.amazonaws.com/my-app/ebc4596f-d7db-340f-b7d6-4952c949f011.jpg' I feel I'm doing something fundamentally wrong. Can an expert guide me via an illustrative example? Thanks in advance. -
Django file upload using Dropzone.js
I am trying to add images to a blog post using Dropzone and Ajax and I cannot manage to upload the files successfully and my post object gets created without the images. I am not seeing any errors in the console but by images are not being added. my image form: class ImageForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ImageForm, self).__init__(*args, **kwargs) self.fields['file'].required = False file = forms.FileField( widget=forms.ClearableFileInput( attrs={ 'multiple': True, 'class':'image_upload_form' })) class Meta: model = Images fields = ('file',) my post_create.html: {% load crispy_forms_tags %} {% load static %} <body> <form id="postCreate" method="POST" data-url="{% url 'home:post-create' %}" class="post-create-form dropzone" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" >Create a Post</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" style="overflow-y: auto; margin:0;"> <div id="loadingDiv"> <div class="d-flex justify-content-center mb-1"> <div class="spinner-border" role="status"> <span class="sr-only">Loading...</span> </div> </div> </div> {{ form|crispy }} <div class="d-flex justify-content-left"> <div> <button type="button" id="upload-image" class="btn btn-sm mr-auto btn-primary pb-1 fileinput-button"> <span><i class="fas fa-image"></i></span> </button> </div> <div> <p class="pt-1 mx-2 text-muted small">Add up to four images to your post</p> </div> </div> <div id="previews" class="dropzone-previews"></div> <div class="fallback"> {{ image_form }} </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" id="submit-all" class="btn btn-primary">Post</button> </div> </form> <script … -
Transfer data from node application to django application both using postgres
How to efficiently insert data from one postgres database to another? I have a legacy node app which I am converting to Django. Both projects are using Postgres. The data schema in node app is vastly different from the new Django app. Therefore, I have written a script that maps old data into new data schema. The problem is that the script is painfully slow. 5 records a second. I have over 1 million records. What is the most efficient way to achieve this? My current script looks like: @transaction.atomic def migrate_users(cursor): select_query = "select * from users order by id" # old database cursor.execute(select_query) records = cursor.fetchall() for row in records: record_dict = {} record_dict['id'] = row[0] record_dict['name'] = row[1] record_dict['email'] = row[2] defaults = { 'name' : record_dict['name'], 'extra' : { 'old_node_db_values' : { 'id': record_dict['id'] } } } u, created = User.objects.get_or_create( email=record_dict['email'], defaults = defaults ) if created: u.set_password(DEFAULT_USER_PASSWORD) u.save() This is a simplified script. Actual data requires a lot of massaging. -
Why is my pagination not working? (Django)
I've been working with Django-Listviews and I used paginate_py in a class to get some pagination going. But it'll just show all the items. This is the class: class PostListView(ListView): model = publicaciones template_name = 'store/search.html' context_object_name = 'queryset' ordering = ['Promocionado'] paginate_by = 2 def get_queryset(self): qs = self.model.objects.all().order_by('id') search = self.request.GET.get('q') if search: qs = qs.filter(Título__icontains=search) return qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) MyFilter = PubFilters(self.request.GET, queryset=self.get_queryset()) context['filter'] = MyFilter context['filtered_items'] = MyFilter.qs context['count'] = self.get_queryset().count() context['búsqueda'] = self.request.GET.get('q') return context Please tell me if I need to post anything else, like filters.py and so on. Thanks in advance! -
FILE PATH can't open with TOKEN in MOD HEADER - UNABLE TO OPEN S3 BUCKET FILE [DJANGO REST]
I've created a REST API app in Django REST. Through it you can upload files to a server, tag them etc. I have connected an S3 AWS bucket as the storage system. The problem is. The app has a token authentication set up. So you get to upload files only if authenticated. BUT when you want to open the file (click on the json link in the displayed data), you have to turn off your mod header with the authentication token, because otherwise it messes up with the opening and tries to input the token in constantly. And this is the better option, for it to at least open like that I had to make the bucket completely public. So the reality is, you post files, with the token authentication on. You can access the api only with the auth token on. But whenever you would want to open a file, you have to turn off the mod header which results in you checking and unchecking the mod header token constantly like an idiot if you want to browse api + open files. Plus because the bucket is public, anybody could see your files... not ideal REST API Serialized data … -
Django: How can I add an aggregated field to a queryset based on data from the row and data from another Model?
I have a Django App with the following models: CURRENCY_CHOICES = (('USD', 'US Dollars'), ('EUR', 'Euro')) class ExchangeRate(models.Model): currency = models.CharField(max_length=3, default='USD', choices=CURRENCY_CHOICES) rate = models.FloatField() date = models.DateField() class Donation(models.Model): date = models.DateField() donor = models.CharField(max_length=250) amount = models.FloatField() currency = models.CharField(max_length=3, default='USD', choices=CURRENCY_CHOICES) I also have a form I use to filter donations based on some criteria: class DonationFilterForm(forms.Form) min_amount = models.FloatField(required=False) max_amount = models.FloatField(required=False) The min_amount and max_amount fields will always represent values in US Dollars. I need to be able to filter a queryset based on min_amount and max_amount, but for that all the amounts must be in USD. To convert the donation amount to USD I need to multiply by the ExchangeRate of the donation currency and date. The only way I found of doing this so far is by iterating the dict(queryset) and adding a new value called usd_amount, but that may offer very poor performance in the future. Reading Django documentation, it seems the same thing can be done using aggregation, but so far I haven't been able to create the right logic that would give me same result. -
When running Django tests using Travis CI, my tests are running and completing locally, but are not running (or being found) remotely
As per the question, I have two tests which I am running successfully on my local machine. Running "python manage.py test" in the command line produces the following output: Creating test database for alias 'default'... System check identified no issues (0 silenced). .. ---------------------------------------------------------------------- Ran 2 tests in 0.495s OK Destroying test database for alias 'default'... These tests are part of a project which is currently residing in a GitHub repository. This repository is linked to Travis CI, and as such, a travis.yml file can be found in the repository's root directory. The contents of the file are as follows: language: python install: - python -m pip install -r requirements.txt before_script: - cd TNI_Project script: - python manage.py test For reference, the "TNI_Project" directory is the one which contains the "manage.py" file, and the "requirements.txt" file contains the output of pip freeze. However, once the build is launched on Travis CI, the build exits with 0, but none of the tests are run. The exact output can be found below: $ python -m pip install -r requirements.txt before_script 0.00s$ cd TNI_Project 0.41s$ python manage.py test System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK The … -
Django models many to many relation adds automatically
I have a model class like this. When I create a student, the django automatically adds all courses to student. class Course(models.Model): course_name = models.CharField(max_length=25) is_open = models.BooleanField(default=True) def __str__(self): return self.course_name class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) EXP = ( ('1', 'Unexperienced LA'), ('2', 'Experienced LA'), ('3', 'Unexperienced TA'), ('4', 'Experienced TA'), ('5', 'DEFAULT'), ) courses = models.ManyToManyField(Course,null=True) exp = models.CharField(max_length=1, choices=EXP) -
Elasticsearch_dsl in django - unable to use password
I want my Django application to use a password for connecting to the elasticsearch container. Therefor I set a connection string in my settings.py which was working fine until I setup password authentication for elasticsearch. Currently I get the following error from Django: elasticsearch.exceptions.AuthenticationException: AuthenticationException(401, '') Using curl like this is working fine inside the container: curl -u "${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD}" "${ELASTICSEARCH_HOST}:${ELASTICSEARCH_PORT" But if I set the same env. vars. for the ELASTICSEARCH_DSL config at my settings.py, I simply fail and cannot establish a connection to elasticsearch due to the auth. failure mentioned above: ELASTICSEARCH_DSL = { 'default': { 'hosts': env.str('ELASTICSEARCH_USERNAME') + str(':') + env.str('ELASTICSEARCH_PASSWORD') + str('@') + env.str('ELASTICSEARCH_HOST') + str(':') + env.str('ELASTICSEARCH_PORT') }, } Is the syntax here maybe wrong for : or @ at the connection string? I already searched the docs and web on this but was not able to find a solution till now. -
nginx configuration with multiple location blocks + React +Nginx
I'm trying to configure nginx for 2 different location. i here is my scenario. www.example.com location : /var/www/example.com example.com/panel location : /var/www/example.com/panel -
How would you get RDKIT to load into an Apache Wampserver for Windows when conventional methods are not working?
RDKIT is the only package not loading into our production server. We successfully set up a Wampserver too run Apache and host our Django project . . .but have to comment out all the code associated with rdkit for it to work. This inhibits many required features. There were no issues using rdkit in Django's test server. Primary wsgi error: from .rdBase import rdkitVersion as __version__\r, referer: http://localhost/APP/ ImportError: DLL load failed: The specified module could not be found.\r, referer: http://localhost/APP/ Relevant packages and version details: Windows 10 Django 2.2 Python 3.7 conda 4.8.2 rdkit 2019.09.3 conda-forge Wampserver 3.2 Apache 2.4.41 mod-wsgi 4.7.1 The methods in this blog describe how we setup the production server. With one minor change, we did not alter the httpd_vhosts.conf file and only setup the standard localhost. The error is reproducible by trying to import rdkit(or one of its methods) into any file needed to host a web application in the described environment. We found this 2016 thread on the rdkit sourceforge and it sounds like someone else was having a similar problem on a Linux system. This is our first time setting up a server and we have not been successful at translating the … -
Multiple Headers in a Python CSV File
I am trying to append rows into columns that I have created using different csv writers and it works well until I try to send it as an email. for school_area in school_areas: sarea = [sar for sar in SchoolArea.objects.filter(school__contains=school_area.city)] csvio = StringIO() header = ['Name', 'Age', 'School', 'Marks', '', 'Name', 'Age', 'Rank'] writer = csv.writer(csvio) writer.writerow(header) csvblank = StringIO() blankheader = [''] blankwriter = csv.writer(csvblank) blankwriter.writerow(blankheader) csvioo = StringIO() headerr = [ '','Total','Average','Median','', 'Total in Class', 'Average in Class', 'Median in Class'] writerr = csv.writer(csvioo) writerr.writerow(headerr) csvioheader = StringIO() header2 = ['Name', 'Age', 'School', 'Marks', '', 'Name', 'Age', 'Rank'] headerwriter = csv.writer(csvioheader) headerwriter.writerow(header2) alert = False alert_list = [] sum_dif_school, sum_dif_uni, classtot, unitot = 0, 0, 0, 0 for school in sarea: data = school_helper() datafill = school_name() row = [] brow=[] drow = [] if data['reports'] > 0.01 or data['reportsuni'] > .01 : row.append(school.name) row.append(round(data['reports'],1)) row.append(round(data['reportsuni'], 1)) row.append('') #blank column if data['reports_school'] > .01 or data['reports_uni'] > .01: row.append(round(data['reports_school'], 1)) row.append(round(data['reports_uni'], 1)) if dif_d > .5 or dif > .5 or dif_d < -.5 or dif < -.5: alert = True alert_list.append(school.name) if data['school'] > 0.01 : brow.append('') brow.append(round(data['total_marks'], 1)) brow.append('') brow.append(round(data['total_reports'], 1)) if data['school'] > 0.01 : … -
Why won't the runserver command in the terminal run? I am (a complete beginner) working on building a web app (learning log) with Django
So I've already created and activated a virtual environment, created a project, and an app (but the app shouldn't really matter at this point). I'm trying to view my project and ran the server command but it won't run. To clarify, I had already made more progress with the web app: created a model and migrated it so i could use it in the app, viewed the project as an admin to see the model working but when i created the second model, i had trouble migrating it. so i took a few steps back to the point where I could just view the empty project and that also didn't work so i'm confused. I could just delete and start over but I'd like to know what's wrong at this point. Below is what the terminal shows when I tried to run 'runserver' command so I could view the project on my local server. C:\Users\acer>cd Desktop/programming/learning_log C:\Users\acer\Desktop\programming\learning_log>ll_env\Scripts\activate (ll_env) C:\Users\acer\Desktop\programming\learning_log>python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line … -
What is Django equivilant to Rails initializers folder?
I have a script for a discord bot that I need to use in a Django App so I can reference the DB and Models from it. The goal is to dynamically output messages to discord based on records. In Rails with the discord gem: https://github.com/discordrb/discordrb I am able to add my script to the initializers folder. This way it starts up and it's always listening. When something like a message or command comes through, I can dynamically update the output message based on the information from the command or message from Discord. Here is my app\config\initializers\discord_bot.rb file: require 'discordrb' bot = Discordrb::Bot.new token: '<>' bot.message(with_text: 'Ping!') do |event| task = Task.find(1) event.respond "Pong! #{task.title}" end bot.run I can access the models from here. This is a quick example but if I wanted, I can check against the discord information I receive to dynamically respond with the bot information from the database records. How am I able to do something similar to this in Django? -
Views/ Django How to read file and show on the page information from file cvs
Please help me to write code to show some values from the cvs file on site. This is my views.py in Django project. On the site views working and show all information from the file.But I need show info by searching for some value and show me line with this value. views.py from django.http import HttpResponse def index(response): with open('news_rss/data.csv', 'r+', encoding='windows-1251') as file: response = HttpResponse(file.readlines()) for line in file: word = 'Contract' if word in line != -1: return (line) return response Somebody can help me to understand how to write correctly this.Thanks a lot -
Passing non form data from Django Template to view
I am working for the contacts app in Django Framework. It sends Otp using Twilio API. Now to send an OTP the view send_message will be called. This view will generate OTP through a random process. Now it will render an HTML template to show that this OTP is going to be sent. If the user clicks to send a new view send_otp will be called that will send the OTP to the recipient. Now My question is how would I get the same value of OTP in the second view that is passed from the first view to the template. Since in the second template I need to send the OTP. Views.py #first view def send_message(request, id): with open('contacts/contact_data.json', 'r') as f: contact_list = json.load(f) for contact in contact_list: if (contact['id'] == id): otp = generate_random_otp() context = { 'otp':otp 'message':text_message, 'id':id } return render(request, 'send_message.html', context) return render(request, 'send_meassage.html', {}) #second view def send_otp(request, id): #I need to pass OTP to this function send date = send(id, otp) return render(request, 'about.html') def send(id,otp): client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) with open('contacts/contact_data.json', 'r') as f: contact_list = json.load(f) for contact in contact_list: if (contact['id'] == id): message = client.messages \ .create( …