Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Computing the final average per grading categories using django
Good day everyone, I just had created my table inside my views.py, I just want to compute the average Per Grading Categories (please see the image of admin Site), This is my data in admin Site studentsgrade = studentsEnrolledSubjectsGrade.objects.filter( Teacher__in=teacher.values('Subjects')).distinct('Grading_Categories').order_by('Grading_Categories') gradingcategories = gradingCategories.objects.filter( id__in=studentsgrade.values_list('Grading_Categories')).distinct().order_by('id') print("gradingcategories",gradingcategories) gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = gradingcategories.values_list('id', flat=True)).filter( grading_Period__in=period.values_list('id', flat=True)).distinct('Grading_Categories') print("gradepercategory",gradepercategory) count_id = studentsEnrolledSubjectsGrade.objects.filter( Grading_Categories__in=cate.values_list('id')).filter( grading_Period__in=period.values_list('id')).order_by( 'id').filter(Students_Enrollment_Records__in = studentenrolledsubject.values_list('id', flat=True)).count() this is the result of print("gradingcategories",gradingcategories) and print("gradepercategory",gradepercategory) gradingcategories <QuerySet [<gradingCategories: Quiz>, <gradingCategories: Homework>]> gradepercategory <QuerySet [<studentsEnrolledSubjectsGrade: Mary M Burabod>, <studentsEnrolledSubjectsGrade: Mary M Burabod>]> when i tried this to my gradepercategory gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = gradingcategories.values_list('id', flat=True)).filter( grading_Period__in=period.values_list('id', flat=True)).distinct('Grading_Categories').aggregate(Sum('Grade'))['Grade__sum'] i get this error error This is how i create my table students = studentsEnrolledSubjectsGrade.objects.filter(Teacher=m.id).filter( grading_Period__in=period.values_list('id')).filter( Subjects__in=student_subject.values_list('id')).filter( Grading_Categories__in=cate.values_list('id')).filter( GradeLevel__in=student_gradelevel.values_list('id')).order_by( 'Students_Enrollment_Records', 'Grading_Categories' ).values('Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname','Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname', 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Middle_Initial','Grading_Categories', 'Grade').distinct() teacherStudents = StudentsEnrolledSubject.objects.filter( id__in=students.values_list('Students_Enrollment_Records')) Categories = list(cate.values_list('id', flat=True).order_by('id')) table = [] student_name = None table_row = None columns = len(Categories) + 1 table_header = ['Student Names'] table_header.extend(list(cate.values_list('CategoryName', flat=True))) table.append(table_header) for student in students: if not student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] == student_name: if not table_row is None: table.append(table_row) table_row = [None for d in range(columns)] student_name = student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] table_row[0] = student_name table_row[Categories.index(student['Grading_Categories']) + 1] = """Result of average … -
Add register on create django
So i'm trying to do a RESTFULL backend for an app on django. So no views needed, right now i'm adding this at the admin. i have created 2 models table 1, and category. Every time i add a table1 row i have to insert 4 categories and budget for every one, initaly 0. i've tried with a method inside table 1 class overriding the save method. and insert when its inserted but i got an error because referential integrity. i have some quiestions. 1.- What is the best way to do this? i've seen on_insert event but i've read as well that is not recomended to work with this. 2.- overide the save method leaving blank the reference to the table1? and then update with the last insert? 3.- other option? class table1(models.Model): table1field = models.CharField(max_length=100,default='') def add_cat(self,cat): category.objects.create(descripcion_categoria_insumo='category 1', category=cat, budget=0) category.save() category.objects.create(descripcion_categoria_insumo='category 2', category=cat,budget=0) CategoriaInsumo.save() pass def save(self, *args, **kwargs): created = self.pk is None super(table1,self).save(*args, **kwargs) # Call the "real" save() method. self.add_cat(self.pk) class category(models.Model): desc_category =models.CharField(max_length=100,default='') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) budget= models.DecimalField(default=0,max_digits=12,decimal_places=2 ,blank=True) category = models.ForeignKey(table1, on_delete=models.CASCADE,blank=True) def __str__(self): return self.desc_category -
How do I get a Django Server Error 500 report
I recently ran my tests on django for my project, one of them turned out as a server error 500. Thi confused me as I thought everything was passing. I currently have DEBUG=True. When I checked the documentation it said to set debug to true and add some admins to email for the full output. Is there an easier way to get the output or should I work on setting that up. For more info my project is still being developed. I dont really want to post my test code as I really need more debugging experience but if you people ask I will! Thanks for any help! -
Short Class Code For My Code For my Homework
class User(): """Represent a simple user profile.""" def __init__(self, first_name, last_name, username, email, location): """Initialize the user.""" self.first_name = first_name.title() self.last_name = last_name.title() self.username = username self.email = email self.location = location.title() self.login_attempts = 0 def describe_user(self): """Display a summary of the user's information.""" print("\n" + self.first_name + " " + self.last_name) print(" Username: " + self.username) print(" Email: " + self.email) print(" Location: " + self.location) def greet_user(self): """Display a personalized greeting to the user.""" print("\nWelcome back, " + self.username + "!") def increment_login_attempts(self): """Increment the value of login_attempts.""" self.login_attempts += 1 def reset_login_attempts(self): """Reset login_attempts to 0.""" self.login_attempts = 0 class Admin(User): """A user with administrative privileges.""" def __init__(self, first_name, last_name, username, email, location): """Initialize the admin.""" super().__init__(first_name, last_name, username, email, location) # Initialize an empty set of privileges. self.privileges = Privileges() class Privileges(): """A class to store an admin's privileges.""" def __init__(self, privileges=[]): self.privileges = privileges def show_privileges(self): print("\nPrivileges:") if self.privileges: for privilege in self.privileges: print("- " + privilege) else: print("- This user has no privileges.") eric = Admin('eric', 'matthes', 'e_matthes', 'e_matthes@example.com', 'alaska') eric.describe_user() eric.privileges.show_privileges() print("\nAdding privileges...") eric_privileges = [ 'can reset passwords', 'can moderate discussions', 'can suspend accounts', ] eric.privileges.privileges = eric_privileges eric.privileges.show_privileges() -
One to many, and one to one combined? Django
class Inquiry(models.Model): inquiry_id = models.AutoField(primary_key=True) inquiry_desc = models.CharField('Inquiry', max_length=5000) class Customer(models.Model): cust_id = models.AutoField(primary_key=True) inquiry_id = models.ForeignKey(Inquiry, on_delete=models.CASCADE) cust_f_name = models.CharField('Customer First Name', max_length=50) cust_l_name = models.CharField('Customer Last Name', max_length=50) cust_street = models.CharField('Customer Street', max_length=50) cust_city = models.CharField('Customer City', max_length=50) cust_state = models.CharField('Customer State', max_length=50) cust_zip = models.CharField('Customer Zip Code', max_length=10) Hi there! I am trying to model a one to many (a customer may have many inquiries) and a one to one (an inquiry may have one customer). Here are my difficulties/what I have tried so far: Inquiries as foreign key in Customer model. This works fine, however, you can only assign one inquiry object per customer. I would like to assign several (so Inquiry1, inquiry2, inquiry3, etc) to the customer. Pictured here/in the code Customer as a OneToOne field in Inquiry (thought this might work for some reason - but as OneToOne work, when I tried to add a a new Inquiry to an existing company it didn't work). I am looking for conceptual advice to do this. I think I'm getting confused. Thank you! -
Django application, vue.js only works if the the vue is in the HTML file
I have a django application, and im using vue.js, however the vue.js only works if the the vue is in the HTML file. As soon as I move it into a separate JS file it no longer work.I'm wondering if i'm missing something super obvious HTML FILE {% extends 'blog/base.html' %} {% block content %} {% load static %} <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11" type="text/javascript"></script> <script src="{% static 'blog/JS/main.js'%}" type="text/javascript"></script> <div class="con"> <button type="button" name="button" @click='addForm()'> new </button> <div class="car-body" v-for="(post, index) in posts"> <span style="float:right;background-color:green" @click='removeForm(index)'> x </span> <h4>Add Article (index:{{ index }})</h4> <div > <input type="text" name="" placeholder="Title" v-models='post.title'> <input type="text" name="" placeholder="Preview" v-models='post.preview'> </div> </div> </div> {% endblock content %} JS file var app= new Vue({ el: '.con', data:{ posts: [ { title:'', preview:'' } ] }, methods:{ addForm(){ this.posts.push({ title: '', preview:'' }) }, removeForm(){ this.posts.splice(index, 1) } } }) -
Getting objects via ManyToMany relation after filter in Django
I have these models: class Notebook(models.Model): title = models.CharField(max_length=200) class Tag(models.Model): name = models.CharField(max_length=63) notebooks = models.ManyToManyField(Notebook, related_name='tags') and I'm trying to find all Notebooks that have two particular tags (I can probably deduce the rest of the query if I can get two tags working) I'm defining a query for the two tags with: query = Q(name__iexact='dna') | Q(name__iexact='notebook') and I can filter the pertinent tags with: Tag.objects.filter(query) But I'm seeking the Notebooks associated with that tag. In SQL I would do a JOIN but the ORM method select_related apparently doesn't work with ManyToManyField -
Django get filenames without upload, filefield?
I have a modelform where I want the user to be able to populate a field with a filename from their local file system, ideally without typing or copy and pasting. I thought a solution might be a django FileField - models.py File = models.FileField(blank=True, null=True, verbose_name='File') This gives the user a nice button -> click filename workflow. I can get this rendering on the form OK but the purpose of FileField is clearly to upload files - I don't want the files to be uploaded, I just want to pick their names. Some of these files are extremely large, so I don't want to interact with them at all other than picking their name. -
How to add choice to Question model by login User
I'm learning django i had an idea to modify poll app from django tutorial. I wanted to add possibility to register and login and then i wanted to do a form where user could create a question and add choices. Firstly i tried to make it on one view, but i thought there will be a problem becouse i heve choice and question in separate models. Then i tried to make one vReverse for 'createChoice' with no arguments not found. 1 pattern(s) tried: ['polls\\/(?P<pk>[0-9]+)\\/choice$']iew for creating question and one for creating Choices, but here i've got this error: I would like to ask for some advice on how to do it. It would be great if i could do it in one page. Here is my code: models.py from django.db import models from django.utils import timezone import datetime from django.contrib import auth # Create your models here. User = auth.get_user_model() class Question(models.Model): question_text = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE, null=False) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) urls.py from django.urls import path, include from django.contrib.auth import views as auth_views from … -
How do i hide items already selected in the checkboxes in Django Admin
So, i have this model on my app: class Loan(models.Model): loan_device = models.OneToOneField(Device, max_length=50, verbose_name='Dispositivo de Empréstimo', on_delete=models.CASCADE, null=True) Important: loan_device it's a One To One relationship with Device model On Django Admin, when someone choose any Device registered, it keeps showing in the checkboxes, even though it was previously selected. My question is: How do i hide items already selected in the checkboxes? -
Footer as a view?
On my footer I have a list of my categories. This means in every page view I loop over all my Category models. I also have a Footer model so I can choose the footer image, so I'm also calling that on every page aswell. I'm wondering if there is a better way to do this.. Here's what I mean: views.py # These are included on every page.. def homepage_view(request): context = { "categories": Category.objects.all(), "footer": Footer.objects.first(), } return render(request=request, template_name='main/index.html', context=context) models.py # Is there a better way to have a dynamic footer image? class Footer(models.Model): footer_image = models.ImageField(upload_to="footer/") class Meta: verbose_name_plural = "Footer" def __str__(self): return "Footer" Is it good practice to have a model just so I can have a changeable footer image? I don't need multiple footer models, I just want to be able to change my footers background image. -
Cómo crear un formulario en Dyango con cabecera y detalle
Necesito crear una forma en Django, similar a una factura con sus líneas de detalle, que se guarde de una sola vez. Por favor me pueden referir ejemplos. Muchas gracias. -
How To Redirect To Same Page After Post a Comment Using Django
as stated in my thread heading, i been on this issue for quite few days. Im trying to redirect to same page i was after making comment of a page irrespective of the paginated comments. Tried altering the get_success_url method but its not working. class ReadThread(MultipleObjectMixin, CreateView): query_pk_and_slug = True form_class = PostForm paginate_by = 3 template_name = 'read_thread.html' context_object_name = 'posts' def get(self, request, *args, **kwargs): self.thread = self.get_object() self.object_list = self.get_queryset() return super().get(request, *args, **kwargs) def get_object(self): thread = super().get_object( Thread.objects.filter(category__slug__iexact=self.kwargs['category_slug']) ) return thread def post(self, request, *args, **kwargs): self.thread = self.get_object() return super().post(request, *args, **kwargs) def get_queryset(self): return self.thread.posts.all() def get_context_data(self, **kwargs): context = super(ReadThread, self).get_context_data(**kwargs) context['thread'] = self.thread return context def form_valid(self, form): form.instance.thread = self.thread form.instance.user = self.request.user return super().form_valid(form) def get_success_url(self): return redirect(self.request.build_absolute_uri(self.thread)) -
Django: Search in Multiple Models
I want to implement a multi model search in django meaning that I want to search different fields in two models. My Two models are "Story" and "Place": from django.db import models from django.utils import timezone from django.contrib.auth.models import User from places.models import Place from django.urls import reverse class Story (models.Model): title = models.CharField(max_length=100,blank=False) content = models.TextField(blank=False) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) Place = models.ForeignKey(Place, on_delete=models.PROTECT) audio = models.FileField(default='SOME STRING', upload_to='audio_stories/',blank=False) class Place (models.Model): name = models.CharField(max_length=100, blank=False) country = models.ForeignKey(Country, on_delete=models.PROTECT, null=True) city = models.ForeignKey(City, on_delete=models.PROTECT, null=True) description = models.TextField(blank=False) location_image = models.ImageField(default='default.jpg', upload_to='location_pics/', blank=False) def __str__(self): return self.name def get_absolute_url(self): return reverse('place-detail', kwargs={'pk': self.pk}) def save(self): super().save() img = Image.open(self.location_image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.location_image.path) def __str__(self): return self.title def get_absolute_url(self): return reverse('story-detail', kwargs={'pk': self.pk}) My View merges both queries. from django.shortcuts import render, get_object_or_404, redirect from django.db.models import Q from django.views.generic import (ListView) from django.contrib.auth.models import User from places.models import Place from .models import Story class SearchResultsView(ListView):# template_name = 'story/results.html' def get_queryset(self): request = self.request query = request.GET.get('q', None) if query is not None: story_list = Story.objects.filter(Q(title__icontains=query)) place_list = Place.objects.filter(Q(name__icontains=query)) results = chain(story_list, place_list) return results … -
Django + Celery with AWS SQS - Running on localhost instead of AWS and not getting messages
Hello I am running Django and Celery on aws SQS, but it appears that AWS is not getting the messages. But the tasks are being executed: Please specify a different user using the --uid option. User information: uid=0 euid=0 gid=0 egid=0 uid=uid, euid=euid, gid=gid, egid=egid, -------------- celery@ba117e7c453f v4.4.0 (cliffs) --- ***** ----- -- ******* ---- Linux-4.9.125-linuxkit-x86_64-with 2020-02-26 20:21:14 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: config:0x7f10e26fada0 - ** ---------- .> transport: sqs://XXXXXXXXXXXXX:**@localhost// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 2 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . config.celery.debug_task . project.orders.tasks.create_log_test [2020-02-26 20:21:14,909: INFO/MainProcess] Connected to sqs://XXXXXXXXXXXX:**@localhost// [2020-02-26 20:21:15,327: INFO/MainProcess] celery@ba117e7c453f ready. [2020-02-26 20:21:32,895: INFO/MainProcess] Received task: project.orders.tasks.create_log_test[d4c20965-b1f2-47dd-b8a8-6f9cbe35be29] [2020-02-26 20:21:53,648: INFO/ForkPoolWorker-2] Task project.orders.tasks.create_log_test[d4c20965-b1f2-47dd-b8a8-6f9cbe35be29] succeeded in 20.695041599974502s: None [2020-02-26 20:22:39,801: INFO/MainProcess] Received task: project.orders.tasks.create_log_test[1d1b0892-078c-480c-ab7a-87662fd18ba3] [2020-02-26 20:22:41,622: INFO/MainProcess] Received task: project.orders.tasks.create_log_test[6e755a91-b737-4e09-b910-03e84fd91c32] [2020-02-26 20:22:43,237: INFO/MainProcess] Received task: project.orders.tasks.create_log_test[5fe1f145-a6d3-45d3-8ada-b1c636ee201c] [2020-02-26 20:22:44,506: INFO/MainProcess] Received task: project.orders.tasks.create_log_test[84da9170-7861-488d-936f-5d3738e11af4] [2020-02-26 20:22:47,056: INFO/MainProcess] Received task: project.orders.tasks.create_log_test[748dda1c-3b6d-40e6-b13b-637ea765dd72] And on AWS console: This is my settings.py: BROKER_URL = "sqs://{access_key}:{secret_key}@".format( access_key=quote(AWS_ACCESS_KEY_ID, safe=""), secret_key=quote(AWS_SECRET_ACCESS_KEY, safe=""), ) BROKER_TRANSPORT_OPTIONS = { "region": "eu-west-1", … -
Hyphenation in Jinja template (using Django Wagtail)
I have a Django Wagtail application, which employs the templating machine Jinja (or Jinja2, not entirely sure, but won't make a difference for this issue). When I e.g. want to use the templating to show the title of a blog post, I can write {{ post.title }} This works perfectly fine. But I cannot enforce hyphenation in this title. If the title holds a very long word, this crashes my layout on small devices. Anyone an idea how I can tell Jinja that hyphenation should be enabled? -
django run custom views class method with one url
I'm new to django. I want to manage my database with custom methods inside the views file. for example, I have this code I would like to run with javascript - I wrote this code: Js: $.ajax({ type: 'POST', url: '/ClassManager/', data: { data: data, csrfmiddlewaretoken: csrftoken, }, success: function() { alert("IT WORKED") }, error: function() { alert('error'); } }) views.py def expfunc(): if request.method == 'POST': user = User.objects.get(pk=1) addlst = List(content = "list content", creator = user) addlst.save() urls.py urlpatterns = [ path('ClassManager/', views.expfunc), ] now, the problem is, that for every new function that I want to create in the views.py, I need to add another line in the urls.py. my question is - if there a way to create a class with all of the custom methods, and access them with one url and different data? for example: Js: $.ajax({ type: 'POST', url: '/ClassManager/functionone()', data: { data: data csrfmiddlewaretoken: csrftoken, }, success: function() { alert("IT WORKED") }, error: function() { alert('error'); } }) views.py class DatabaseManager(): def functionone(): # add new list if request.method == 'POST': user = User.objects.get(pk=1) addlst = List(content = "list content", creator = user) addlst.save() def functwo(): # update username if request.method … -
Django change foreign keys to BigInt
I have two models (store and products) the primary key in both are BigInt but the relation column in products (store_id) is still integer. I dont want to use raw sql, how can I fix this issue using django? -
Passing variable from HTML to Python file with Django
I am trying to have a user input their information in the HTML form and then send it to my Python app that is located in the root of the directory and then run the python program. Below is my code for views.py and my html form. How do I pass a variable from the HTML to my Python app and then execute the program? views.py def shopbotView(request): context = {} if request.method == 'POST': user_first_name = request.POST.get('user_first_name') user_last_name = request.POST.get('user_last_name') user_email = request.POST.get('user_email') user_phone = request.POST.get('user_phone') user_address = request.POST.get('user_address') user_zipcode = request.POST.get('user_zipcode') user_city = request.POST.get('user_city') return render(request, "index.html", context) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <div class="jumbotron jumbotron-fluid"> <div class="container"> <h1 class="display-4">Flatbush Zombies Shop Bot</h1> <p class="lead">This is a bot written in Python that will shop <a href="https://thegloriousdead.com/">this</a> website for you. This website sells out of its products right away when they are released so this bot can purchase your desired items in an instant!</p> </div> </div> <div class="form"> <form action="#" method="POST"> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroup-sizing-default">First name</span> </div> <input id="first_name" type="text" name="user_first_name" value="{{ user_first_name }}"> </div> <div class="input-group mb-3"> <div … -
Django - Class Based View for a specific item
Building a Django app where I have a view that displays a list of distinct case. When you click on a case, I'd like it to take you to a list of items related to the case (in this case it's a list of devices). The issue I am facing I don't know how to make the view display only the items related to that case (right now it displays every item in every case). Views: class MdeListView(LoginRequiredMixin, ListView): model = Mde template_name = 'mde/mde.html' ordering = [F('date').desc()] def get_queryset(self): return Mde.objects.distinct('case_number') class MdeCaseListView(LoginRequiredMixin, ListView): model = Mde template_name = 'mde/mde_case_list.html' urls.py from django.urls import path from .views import MdeListView, MdeCreateView, MdeCaseListView urlpatterns = [ path('<int:pk>/list', MdeCaseListView.as_view(), name='mde_case_list'), path('new', MdeCreateView.as_view(), name='mde_new'), path('', MdeListView.as_view(), name='mde'), ] The url goes to the right record based on the primary key, but from there I want only the items that use the same case_number as that primary key. -
sending notification/message to chosen users in Django
I am working on a part of a project that when I create a group for a project and once I submit the form (where I can pick certain users to be in the group in the form), the users who I selected in the form will receive any type of notification. The idea I am having now is when the selected users log in, their web pages will receive the notification that they are selected to the group. I have looked at Django's message frameworks however, it seems like they don't have the information that I am looking for. Can anyone please give me suggestion on where to start and what should I look at? -
How to import data from django.models, to use in javascript?
I am trying to import a python dictionary from moodels and manipulate/print it's properties in Javascript. However nothing seems to print out and I don't receive any error warnings. Views.py from chesssite.models import Chess_board import json def chess(request): board = Chess_board() data = json.dumps(board.rep) return render(request, 'home.html', {'board': data}) Here board.rep is a python dictionary {"0a":0, "0b":0, "0c":"K0"} - basically a chess board home.html <html> <body> {% block content %} <script> for (x in {{board}}) { document.write(x) } </script> {% endblock %} </body> </html> I also would very much appreciate some debugging tips! Thanks in advance, Alex -
Calling two views in third Django view
i have a little scraping script which i try transfer to django. My problem is i want call two views (which should return something) in third view but it is not working. Here are my views: def create_request(url): req = Request( url, data=None, headers={ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36' } ) return req def get_request(req): return urlopen(req).read() def scraping(request): link = 'https://www.transfermarkt.pl/schnellsuche/ergebnis/schnellsuche?query=' data = request.POST.get("textfield") if data is None: return '' else: search = link + data + '&x=0&y=0' eleven = urllib.urlopen(search) soup = BeautifulSoup( get_request(create_request(eleven)), #here i got stuck features="lxml" ) anchor = soup.find("a",{"class":"spielprofil_tooltip"}) #here appears rest of code where i scrap some data Now i got stuck on the line when i define soup variable. In this line of code i use two earlier views: 'get_request' and 'create_request' but i am probably doing it wrong. I search for some directions but i didn't find anything and i have no idea how to implement it. How should i use that views to make this third view working good? -
Image is not uploading to the existing directory by Django model- ImageField(upload_to='')
I'm using Django 3. My Django model has an ImageField() as shown below: item_image = models.ImageField(upload_to='static/ims/images') The directory to which I want to save my image is already existing but still, it creates another file same as the mentioned location. Like so, static |__ims |___images |___**saved images** But, I want the image to save in the mentioned location which already exists (see below) static | |__ims | |__images | |___**images to be saved** |___style.css Can anyone help save my images to the pre-existent static directory? -
Error in loading two different pickle model in Django
I have a Django APP where in view.py I have included two different pickle model load as following: model = pickle.load(open(os.path.join(settings.STATIC_ROOT,'randomforest.sav'),"rb")) model2 = pickle.load(open(os.path.join(settings.STATIC_ROOT,'svm.sav'),"rb")) and then I set the two model as following: classification = model.predict(X_test) classification2 = model2.predict(X_test2) But now when I print the result of the prediction, the two classifier returns: 'from model 1' [1. 0.] 'from model 2' [1. 0.] even if SVM classifier should return just the classification as: [2] it seems that the second model (i.e., model2) doesn't be loaded or properly called. How may I do to solve that issue? Just to be clear: While using the same logic, for instance, in colab I obtain the following, correct, results: [[1. 0.]] [2]