Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django-channels create one instance of class for each room
I am using django-channels to make a small webgame. So far, I've been able to connect the client to the server and have different consumers in the same room/lobby (same as in the channels tutorial, where a room is defined by it's url) sending data to each other. The problem I'm having is that currently, every time any consumer connects to the server, a new game instance is created. However what I would like to do instead is have one game instance per room, so the moment a room is created, a game instance is started. Where can I initialise the game in such a way that the consumer class in that lobby also has access to it? -
Django template table with missing data for some columns
Okay, I give up. I searched through and through and lost something that looked like an answer, so I have to ask. Say, data for a regional power grid and each power plant has a production plan for a day, all of them go as list of dicts with a plan for every hour. Data also include a power consumption forecast, which naturally only has data for hours in the future. [ {'station_id':'Grid','plan_code':1000,'plan':{1:300,2:500,3:250,...,23:519,24:200}} {'station_id':'Plant1','plan_code':1001,'plan':{1:100,2:224,3:150,...,23:239,24:100}} {'station_id':'Plant2','plan_code':724,'plan':{1:200,2:226,3:100,...,23:240,24:100}} #every hour contains value {'station_id':'Consumption','plan_code':2003,'plan':{21:1600,22:1710,23:1250,24:1100}} #only few hours have data ] What I'm trying to generate with Django template is a table of power grid production, consumption and balance values: <table> <thead> <tr style="font-size: small"> <th>Plan for</th> <th>Type</th> <th>01</th> <th>02</th> <th>03</th> ... <th>22</th> <th>23</th> <th>24</th> </tr> </thead> <tbody> {% for plan in plans %} <tr style="font-size: small"> <td>{{ plan.station_id }}</td> <td>{{ plan.plan_code }}</td> {% for hour,val in plan.plan %} <td>{{ val }}</td> {%endfor%} </tr> {% endfor %} </tbody> </table> The questions are: How dow I determine order in which plans are displayed? How do I fill a row with consumption plan with empty cells if no value is provided for that hour? Please, help a beginner here. -
How to annotate a Django QuerySet with a Point?
Lets say I have a model A that has fields lat(FloatField) and lon(FloatField). I want to annotate the QuerySet using a point: A.objects.annotate(point = Value(Point('lat', 'lon'), output_field=PointField())) I keep on getting TypeError('Invalid parameters given for Point initialization.') For some reason Django is not recognizing the fields and instead is passing them as strings (I think). How do I accomplish this? Thanks -
How to mock a function in a file?
I have a function in a file generate_new.py: def generate_new(): return ''.join(["{}".format(randint(0, 9)) for num in range(0, 4)]) Iam using the following decorator to mock the function. but it dosn't work! class TestPhoneVerify(APITestCase): def generate_token(): foo = ["11111", "22222"] return random.choice(foo) @mock.patch('lenmo.phoneverify.utils.generate_new.generate_new', side_effect=generate_token) def x(self, token): /do sth but "generate_token" function output doesn't replace "generate_new" in generate_new file! -
Why Django doesn't wrap [] or SELECT to ARRAY in case of using Array field?
For example I have such query as: Chat.objects.filter(users__contains=[user.pk]).filter(users__contained_by=mentors.values_list('pk', flat=True)) This turns to such query: SELECT "chat_chat"."created_at", "chat_chat"."updated_at", "chat_chat"."id", "chat_chat"."users" FROM "chat_chat" WHERE ("chat_chat"."users" @> [1]::integer[] AND "chat_chat"."users" <@ (SELECT V0."id" FROM "users_user" V0 INNER JOIN "users_userrequest_mentors" V1 ON (V0."id" = V1."user_id") WHERE V1."userrequest_id" IN (SELECT U0."id" FROM "users_userrequest" U0 WHERE U0."user_id" = 1))::integer[]) If I run this query , I'll face the problem of casting. cannot cast integer to integer[] But the documentation of Postgres says that arrays should be used as ARRAY[1,2,...,4] So I've wrapped [1] and (SELECT ...) to ARRAY like SELECT "chat_chat"."created_at", "chat_chat"."updated_at", "chat_chat"."id", "chat_chat"."users" FROM "chat_chat" WHERE ("chat_chat"."users" @> ARRAY[1]::integer[] AND "chat_chat"."users" <@ ARRAY(SELECT V0."id" FROM "users_user" V0 INNER JOIN "users_userrequest_mentors" V1 ON (V0."id" = V1."user_id") WHERE V1."userrequest_id" IN (SELECT U0."id" FROM "users_userrequest" U0 WHERE U0."user_id" = 1))::integer[]) And everything works fine. I'm just curious why Django (or psycopg2) skip this wrapping. Is there any special meaning for such behavior ? -
DRF Post to ViewSet without writing into Model
I've always written data into database when posting via Django Rest Framework endpoints. This time I would like to process received data and send it somewhere else without writing into DB. I switched from ModelViewSet to ViewSet, I can issue GET request OK but receiving Bad Request 400 when I curl or POST via DRF URL. Here's a working minimal code (removed need for authentication etc): urls.py from django.urls import path, include from .views import ContactView from rest_framework import routers router = routers.DefaultRouter() router.register('message', ContactView, basename='message') urlpatterns = [ path('', include(router.urls)), ] serializers.py from rest_framework import serializers class ContactSerializer(serializers.Serializer): text = serializers.CharField(max_length=250) views.py from rest_framework.response import Response from .serializers import ContactSerializer from rest_framework import viewsets class ContactView(viewsets.ViewSet): def list(self, request): return Response('Got it') def create(self, request): serializer = ContactSerializer(data=request.data) if serializer.is_valid(): return Response(serializer.data) else: return Response('Invalid') Would greatly appreciate your suggestions. -
Django Do Not Use One Model Of Third Party App
In the app django-cookie-consent, I do not want to use the following table: https://github.com/bmihelac/django-cookie-consent/blob/master/cookie_consent/models.py#L105-L119 When a user accepts/declines a cookie, a log entry in the database is created. But users could abuse this and spam click the buttons and fill up the database. Or I need a way to create a setting for settings.py to disable/enable the logging functionality completely without breaking the app since admin.py and util.py of that app have code associated with this model. How would you go about doing something like this? -
search_field cannot accept query from User model
i tried to make search field to search by author in the admin panel but i got an error Related Field got invalid lookup: icontains i follow the documentation and other stackoverflow question but it doesn't work @model.py from django.contrib.auth import get_user_model User = get_user_model() class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return str(self.user) # Create your models here. class Post(models.Model): title = models.CharField(max_length=256) content = models.TextField(verbose_name='content') date_published = models.DateTimeField(auto_now_add=True) date_edited = models.DateTimeField(auto_now=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField(blank=True) def __str__(self): return self.title @admin.py from django.contrib import admin from .models import Post, Author, class PostAdmin(admin.ModelAdmin): list_display = ['title', 'date_published', 'date_edited', 'author', ] search_fields = ['title', 'author__user',] admin.site.register(Post, PostAdmin) admin.site.register(Author) it works when i changed the search_field[1] to author__id, but since it only accept id, it can't get the username. any idea how to solve it? should i make custom user model? -
How to register/login a user with django oauth toolkit
I've been trying to implement oauth2 authentication system to my register/login system. The problem I'm facing is django-oauth-toolkit docs don't explain how to register a user, like what I should do with my register/login APIView. I know that I should get client_id and client_secret after creating a user and use them while logging in but don't know how to implement that logic to my views. So there is my code: views.py class UserRegisterAPIView(generics.CreateAPIView): queryset = CustomUser.objects.all() serializer_class = UserCreateSerializer class UserLoginAPIView(APIView): serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=HTTP_200_OK) return Response(serializer.errors, HTTP_400_BAD_REQUEST) -
SHH port forwarding with Nginx and Gunicorn web server not working
I want to host a Django web app that runs on my local workstation with no static public IP address. I've got a Linux server with a public IP address, which I want to use as a proxy to my web app so as to make it available to the outside world. I've setup Nginx with Gunicorn locally, and it works just fine when tested locally. Here's what my nginx conf file looks like: # /etc/nginx/sites-available/default server { listen 8020; server_name <my public server ip>; location / { proxy_pass http://127.0.0.1:8010; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /static { root /workspace; } } I start my gunicorn and nginx servers with: (gunicorn API.wsgi --user www-data --bind 0.0.0.0:8010 --workers 3) & nginx -g "daemon off;" Note: wsgi is stored in the API module of my web app source code and the Gunicorn server is running at 8010 and Nginx is running at 8020. Now, I want to access my site on <my public server ip>:8020, for that I'm doing a reverse SSH tunneling from my local workstation to my public server. My ssh command looks like this: ssh -R 8020:localhost:8020 ubuntu@<public server ip> -i private_key.pem I'm not able to access … -
From FBV to CBV with multiple forms
So I deal with multiple forms in my view, which as far as I get disallow the use of a FormView. But is there a way to convert it to a Formview or any other CBV? And how would I approach this. My view: def new_invoice(request): InvoiceItemFormset = inlineformset_factory(Invoice, InvoiceItem, fields=('service', 'unit_price', 'quantity', 'vat_rule', 'unit')) if request.method == 'POST': invoice_form = NewInvoiceForm(request.POST) if invoice_form.is_valid(): invoice = invoice_form.save(commit=False) invoice.user = request.user invoice.save() formset = InvoiceItemFormset(request.POST, instance=invoice) if formset.is_valid(): formset.save() return redirect('dashboard:dashboard') else: formset = InvoiceItemFormset() invoice_form = NewInvoiceForm() context = { 'invoice_form': invoice_form, 'formset': formset, 'invoice': Invoice, 'time': date } return render(request, 'dashboard/new-invoice.html', context) -
Form save is not adding user to model
I have a django Model and ModelForm, but when I make a new body, everything works, except the User is not created. All post.user attributes return none. I am using the contrib.auth to login user, which works as in my html user.is_authenticated works I tried using: form.user=request.user form.save() to no avail. Any help would be appreciated Models.py from django.db import models from datetime import datetime from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): body = models.TextField(max_length=140) timestamp = models.DateField(db_index=True, default=datetime.utcnow) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) class Meta: ordering = ['-timestamp'] def __repr__(self): return '<Post {}>'.format(self.body) def get_absolute_url(self): return reverse('post', args=[str(self.id)]) Forms.py from django.forms import ModelForm from .models import Post from django.core.exceptions import ValidationError class PostForm(ModelForm): def clean_body(self): data = self.cleaned_data['body'] if len(data) > 140: raise ValidationError('More than 140 characters') return data class Meta: model = Post fields = ['body'] views.py from django.contrib.auth.decorators import login_required from django.urls import reverse from django.core.paginator import Paginator from django.shortcuts import redirect, render from .models import Post from .forms import PostForm from django.contrib.auth.models import User # Create your views here. @login_required def index(request): '''deal with post method first''' if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save() return … -
How to get data and post to DB in Django
I have created a form and want to post those data to DB but no error and no data build up after submitted. the Model I created: class BillingAddress(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) street_address = models.CharField(max_length=100) apartment_address = models.CharField(max_length=100) district = models.CharField( max_length=2, ) def __str__(self): return self.user.username Th forms.py in my project class CheckOutForm(forms.Form): street_address = forms.CharField(widget=forms.TextInput()) apartment_address = forms.CharField(required=False) district = forms.ChoiceField(widget=forms.Select(attrs={'class': 'custom-select d-block w-100',}), choices=DISTRICT_CHOICES,) same_billing_address = forms.BooleanField(widget=forms.CheckboxInput()) save_info = forms.BooleanField(widget=forms.CheckboxInput()) payment = forms.ChoiceField(widget=forms.RadioSelect, choices=PAYMENT_CHOICES) The html code: <form method="POST" class="card-body"> {% csrf_token %} <h3>Shipping address</h3> <div class='hideable_shipping_form'> <div class="md-form mb-5"> <label for="street_address" class="">Address</label> {{ form.street_address }}..... views.py. I think I might wrong here but I can't figure it out def checkout(request): form = CheckOutForm(request.POST or None) if request.method == 'POST': street_address = form.cleaned_data.get('street_address') apartment_address = form.cleaned_data.get('apartment_address') district = form.cleaned_data.get('district') same_billing_address = form.cleaned_data.get('same_billing_address') save_info = form.cleaned_data.get('save_info') payment = form.cleaned_data.get('payment') billing_address = BillingAddress( user=request.user, street_address=street_address, apartment_address=apartment_address, district=district, ) billing_address.save() return redirect('checkout') else: form = CheckOutForm() context = { 'form': form } return render(request, 'product/checkout.html', context) -
how to save dictionary in django
i want to save this dictionary crypto_dict into django model i tried to take input from html tags but it didn't work i also tried to put model object and save method inside the loop but that also didn't work please help i am new to django i am stuck here this is my views : from .models import crypto import requests, time class CryptoData: def __init__(self): self.usd_url = "https://api.coingecko.com/api/v3/coins/markets?" \ "vs_currency=usd&order=market_cap_desc&per_page=250&page=1" \ "&sparkline=false&price_change_percentage=24h" self.gbp_url = "https://api.coingecko.com/api/v3/coins/markets?" \ "vs_currency=gbp&order=market_cap_desc&per_page=250&page=1" \ "&sparkline=false&price_change_percentage=24h" self.previous_request = None self.crypto_dict = dict() def get_crypto_data_dict(self, request, seconds_to_wait=60): if not self.previous_request or self.previous_request+seconds_to_wait < time.time(): print("requested", self.previous_request, time.time()) self.previous_request = time.time() crypto_dict = dict() requests1 = requests.get(self.usd_url) results1 = requests1.json() requests2 = requests.get(self.gbp_url) results2 = requests2.json() for i in range(0, 250): self.crypto_dict[results1[i]['id']] = { 'coin_name': results1[i]['name'], 'coin_id': results1[i]['symbol'], 'usd': results1[i]['current_price'], } coin_id = request.POST.get('coin_id', '') coin_name = request.POST.get('coin_name', '') coin_price = request.POST.get('coin_price', False) coin_info = crypto(**self.crypto_dict) coin_info.save() return self.crypto_dict crypto_data = CryptoData() def home(request): context = { 'crypto_data': crypto_data.get_crypto_data_dict(request) } return render(request, 'crypto/home.html', context=context) this is my models.py: from django.db import models class crypto(models.Model): coin = models.CharField(max_length=25) symbol = models.CharField(max_length=10, default="", editable=False) price = models.FloatField() def __str__(self): return self.coin -
Unique Integrity Error on Email Field (Not User model)
I am getting this error when trying to create a Member (note that this is not the User model) with an email that already exists: duplicate key value violates unique constraint "members_member_email_key" DETAIL: Key (email)=(myemail@gmail.com) already exists. The email field for the Member model looks like this: email = models.EmailField(max_length=255, unique=False, primary_key=False) Why am I getting this error if unique is set to False and it is not a primary_key? Thanks! -
Django - Getting matching query does not exist
my template has three columns in one form where they work separately. If I give input for contact column and male column it will save in my database. So basically I want to update the male only as contacts,male and from are present in same html form. I can update the contact but not the male or female inputs. They all are in same page.I want to make working differently so I can update them. views.py def update(request,pk_test): template_name = 'update.html' contact = Contact.objects.all() # c_form = commentForm(instance=contacts) # if request.method =='POST': # c_form = commentForm(request.POST,instance=contacts) # if c_form.is_valid() : # contact = c_form.save() # messages.success(request, "Contact Updated") # return redirect("success") # else: # c_form = commentForm() # context = { # 'c_form' : c_form, # } contacts= Male.objects.get() male_f = maleForm(instance=contacts) if request.method == 'POST': contact_m.save() c_form = commentForm(request.POST) male_f = maleForm(request.POST,instance=contacts) if male_f.is_valid(): contact_m = male_f.save(commit=False) contact_m.contact1 = contact contact_m.save() messages.success(request, "Contact Updated") return redirect("success") else: male_f = maleForm() context = { 'male_f' : male_f } return render(request , template_name , context)``` models.py class Male(models.Model): contact1 = models.ForeignKey(Contact, on_delete=models.CASCADE,null=True) chest = models.CharField(max_length=30 , blank=True) neck = models.CharField(max_length=30 , blank=True) full_shoulder_width = models.CharField(max_length=30 , blank=True) right_sleeve = models.CharField(max_length=30 , … -
how to setup django with apache 2.4 and python3
I am using amazon ec2. I have installed httpd 2.4 python3, pip3. Here is my script which I use to set up. #!/bin/bash yum update -y yum install httpd httpd-devel python3 python3-pip git gcc python3-devel -y cd /var/www/html groupadd www usermod -a -G www apache usermod -a -G www ec2-user cd /opt mkdir django chmod ug+s /opt/django chmod ug+wr -R /opt/django cd /opt/django chown -hR apache:www /opt/django su ec2-user -c 'cd /opt/django; sudo pip3 install virtualenv mod_wsgi' su ec2-user -c '' su ec2-user -c 'virtualenv -p python3 connect_api' su ec2-user -c 'sudo git clone https://copyrepo' chmod ug+s /opt/django chmod ug+wr -R /opt/django chown -hR apache:www /opt/django su ec2-user -c 'cd /opt/django/api; source ../connect_api/bin/activate; sudo pip3 install -r requirements.txt' su ec2-user -c 'cd /opt/django/api; source ../connect_api/bin/activate; sudo pip3 install django' yum remove -y gcc python3-devel httpd-devel ln -s /usr/local/lib64/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so /usr/lib64/httpd/modules/mod_wsgi.so echo LoadModule wsgi_module modules/mod_wsgi.so > /etc/httpd/conf.d/wsgi.conf su ec2-user -c 'echo export SECRET_KEY=al3^qak1limt+3l%*rtk1elula*$z^%a9wt+oao%mri$u3qhya >> ~/.bashrc' su ec2-user -c 'echo export DEBUG=1 >> ~/.bashrc' su ec2-user -c 'echo export EMAIL_BACKEND=django.core.mail.backends.console.EmailBackend >> ~/.bashrc' su ec2-user -c 'echo export ENVIRONMENT=local >> ~/.bashrc' su ec2-user -c 'echo export ALLOWED_HOSTS=[10.0.0.0/24,domainaws] >> ~/.bashrc' su ec2-user -c 'echo export DATABASE_ENGINE=django.db.backends.postgresql_psycopg2 >> ~/.bashrc' su ec2-user -c 'echo export DATABASE_NAME=dbname >> … -
How to execute a javascript function above two columns and return as a third column?
I had an webpage that compares two .docx file and returns the lines where the files don't match. I want to create a diff column where the diff between the strings(I may handle the return as strings) are 'highlighted'. My html page is renderized by django in the following way: <table class="table" border="1px"> <thead class="thead-dark"> <tr> <th scope="col">Arquivo Original</th> <th scope="col">Arquivo Secundário</th> </tr> </thead> <tr> {% for _, record in check.iterrows %} <tr> {% for value in record %} <td>{{ value }}</td> {% endfor %} </tr> {% endfor %} </tr> </table> <script> I would like to apply this htmldiff function (https://ourcodeworld.com/articles/read/653/how-to-diff-html-compare-and-highlight-differences-and-generate-output-in-html-with-javascript), creating a third column where the highlight diff are going to be returned. I can dynamically create a 'Diff' column, but I don't know how to populated that column. Following the link above, the function can be called as the following: // Diff HTML strings let output = htmldiff(originalHTML, newHTML); document.getElementById("output").innerHTML = output; Is there a way to return the function as a third column? The working application can be find here https://jurisfai.herokuapp.com/documentcomparer/, I am trying to better the visualization creating a third column. Thank you, have a nice day. -
How to structure User - Team - Project model Django (ManyToMany)
I'm hoping someone can give me a push in the right direction, at least conceptually. What I'm trying to achieve; a model where: You have users, teams and projects; Teams should always be linked to a project (i.e. they exist "in" projects) Users can be linked to a project without being a team; Users can be in multiple teams and projects I've read something about Models Managers before, should I use these? Something else I'm struggling with is that users can/should be linked to projects directly or though a team, will this cause problems? below some snippets from the models.py file class User(models.Model): email = models.EmailField( verbose_name='email address', max_length=255, unique=True ) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Workstream(models.Model): name = models.CharField(max_length=100) project = models.ForeignKey(Project, on_delete=models.CASCADE) members = models.ManyToManyField(User) #Like this? class Project(models.Model): name = models.CharField(max_length=100) members = models.ManyToManyField(User) #Like this? Any help in the right directions will be greatly appreaciated! -
FieldError at /post/new
I'm using Django 3.0.8 in Python version 3.8.2 I'm getting an FieldError at /post/new/ Exception Type: FieldError Exception Value: Unknown field(s) (content) specified for Post PostCreateView is a class-based view in my views.py of under the blog app of my current project My blog/views.py is here:- from django.shortcuts import render from .models import Post from django.views.generic import ( ListView, DetailView, CreateView, ) # Create your views here. def home(request): context = { 'posts': Post.objects.all() } return render(request, 'blog/home.htm', context) def about(request): return render(request, 'blog/about.htm', {'title': 'About'}) # return HttpResponse('<h1> Blog - About page that we want you to see </h1>') def order(request): return render(request, 'blog/order.htm') class PostListView(ListView): model = Post template_name = 'blog/home.htm' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] class PostDetailView(DetailView): model = Post class PostCreateView(CreateView): model = Post fields = ['title', 'content'] My blog/urls.py is here: from django.urls import path from . import views from .views import ( PostListView, PostDetailView, PostCreateView ) urlpatterns = [ path('about/', views.about, name='blog-about'), path('order/', views.order, name='blog-order'), path('', PostListView.as_view(), name='blog-home' ), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail' ), path('post/new/', PostCreateView.as_view(), name='post-create' ), ] My blog/templates/blog/post_form.html is here:- {% extends "blog/base.htm" %} {% load crispy_forms_tags %} {% block content %} <div class="context-section"> <form method="POST"> {% csrf_token %} … -
not able to use bootstrap in my django project
Bootstrap CDN is not working in my project and I am not able to use the classes of bootstrap in my Django project can anyone tell me the steps to configure my Bootstrap so that i can use it. -
Why is my ManyToManyField in Django returning only one value?
In my Django project, I have a class with a ManyToManyField: class ContestCategory(models.Model): name = models.CharField(max_length=70, blank=False, null=False) judges = models.ManyToManyField('users.CustomUser', null=True) I can see after migrating that everything worked fine and the table is created. I made a form to change the judges like this: class JudgesForm(forms.ModelForm): class Meta: model = ContestCategory fields = ['judges'] def __init__(self, *args, **kwargs): super(JudgesForm, self).__init__(*args, **kwargs) In my view, the form appears and correctly displays all the CustomUser objects there are, and shows no error when saving. However, in my post method, when I do this: class SubmissionCategoriesDetailView(LoginRequiredMixin, DetailView): model = ContestCategory template_name = 'reportes/detail_submission_categories.html' form_class = JudgesForm def post(self, request, *args, **kwargs):# 1711 5656 2230400 7616 pk_category = kwargs.get('pk') judges = request.POST.get('judges') logging.info(str(judges)) return HttpResponseRedirect(reverse('reportes:submission_categories')) I get in the logs that 'judges' returns the correct Id of my CustomUser but only if I have just one CustomUser selected. Whenever I choose more than one, it only gives me in 'judges' the Id of the last one that was chosen, not of all of them. Why is this happening? Should I use a different widget than the automatic one or is there something missing from the models? Any help would be appreciated. -
PureWindowsPath has no attribute 'seek'
I'm trying to deploy a DL model built using Fastai2 library using Django. As I'm using windows machine I used PureWindowsPath(), path=PureWindowsPath('./artifacts') model=load_learner(path/'learn.pkl') But this throws an error- " PureWindowsPath has not attribute 'seek'. You can only torch.load from a file that is seekable. How do I solve this? Thanks, -
Why isn't one function loading my model into a database even though it works for a different model?
I am trying to load 500 instances of two different models into my Django database. I wrote a migration to accomplish this, which runs a function for each model that loads the required instances into the database. The two functions are exactly the same except for the type of model it creates. However, for some reason, only the first function (loadSongs) properly loads the functions into the database correctly. The second function (loadAlbums) immediately yeilds a TypeError and says that an object of "NoneType" is not callable. I've already made sure that the array I pass into bulk_create is not empty, and every instance of the model seems to be saving into the array properly. Does anyone know what the issue might be? Here are the two functions I am calling: from bs4 import BeautifulSoup import numpy as np from ..models import Song,Album from django.db import migrations import requests from time import sleep from random import randint # Create function to load song data into table def loadSongs(apps, schema_editor): # Initialize counter to iterate through site pages, initialize album rankings, create model, then scrape pages one by one links = np.arange(1,11,1) rank = 500 songList = [] for link in … -
How to prevent angular 1.2 controller from reloading while changing django template
I'm building a web application using AngularJS 1.2 and Django. In the webapp, I'm using django for routing and rendering respective html templates. AngularJS functionality is limited to controlling DOM behaviour and rest calls. Here's the code from my index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head></head> <body ng-app="dwitterAngularModule"> <div ng-controller="dwitterCtrl" id="homepage-div"> <div class="container-fluid"> <div class="row"> <div class="col"> <img src="{% static 'images/dwitter_favicon.png' %}" height="42" width="42"> </div> <div class="col-6"> <div id="search-box-div"> <div><img src='libraries/octicons/icons/mention-16.svg' alt="icon name"></div> <div><input type="text" class="sky-back search-box" placeholder="Search Dwitter"></div> </div> </div> <div class="col"> </div> </div> </div> <div class="container-fluid"> <div class="row"> <div class="col"> <nav class="menu-navigation"> <a class="options-menu-item" ng-repeat="item in menuItems" ng-href="[[item.url]]"> <div class="nav_pad"> <img ng-src="libraries/octicons/icons/[[item.icon]]-24.svg" alt=[[item.name]]> &nbsp; <span ng-bind="item.name"></span> </div> </a> <a class="m_t" data-toggle="modal" data-target="#addDweetModal"> <div class="dark-sky-back dweet-btn nav_pad"> <span>Dweet</span> </div> </a> </nav> <div class="nav_pad"> <!-- Logged in user info --> <div><!--profile image--></div> <div> <div ng-bind="currentUser.fullname"></div> <div class="font-light"> <img src='libraries/octicons/icons/mention-16.svg' alt="icon name"> <span ng-bind="currentUser.username"></span> </div> </div> </div> </div> <div class="col-6"> {% block content %} {% endblock %} </div> <div class="col"></div> </div> </div> </div> </body> </html> Index.html is my base template for django and all other templates render between jinja code block. Also, as you can see I've declared angular controller dwitterCtrl on the div outside the jinja block, …