Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot install whitenoise
I am attempting to run the command pip install django-heroku, but whenever I do, it stops with the error ERROR: Package 'whitenoise' requires a different Python: 2.7.16 not in '>=3.5, <4'. I have tried to run pip install whitenoise, but that doesn't work. Same error. I am using Python 3.8.2 -
Django model form, not saving to DB correctly
I've looked at a couple of other questions on here, but can't seem to get any results.. I don't seem to get any errors thrown at me, so I'm not sure where I'm going wrong. I believe I may be using the primary key incorrectly. I do not want to put 'User' under my model form as it would allow someone to change someone else's fields. class history(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) gallons_requested = models.IntegerField() delivery_address = models.CharField(max_length=100) delivery_date = models.DateField() suggested_price = models.DecimalField(max_digits=6, decimal_places=2) total_amount_due = models.DecimalField(max_digits=6, decimal_places=2) def testing(request): if request.method == 'POST': form = RequestForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('pricing_module') else: form = RequestForm(instance=request.user) args = {'form': form} return render(request, 'pricing_module.html', args) -
how can i get all the data from my model booking having date less than today i want to show the booking history of customer
view.py def Profile(request,uid): book =booking.objects.filter(user=uid) user =User.objects.get(id=uid) books = booking.objects.filter(created__lt=datetime.today(),user=uid) params={'book':book,'user':user,'books':books} return render(request, 'hotel/userProfile.html',params) -
windows django data source name not found and no default driver specified
I'm trying to connect to SQL Server studio v17.2 This is the code that works fine in my local computer DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'ENGINE': 'sql_server.pyodbc', 'NAME': 'database', 'HOST': '10...', 'USER': 'user', 'PASSWORD': 'password', #'DRIVER':'ODBC Driver 17 for SQL Server' 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server',} } } This is the error I am getting: windows django data source name not found and no default driver specified -
How to test if the billing address provided is linked to the card number Stripe
I am trying to implement stripe in my website. I am using the test mode of stripe and using their provided card numbers for testing purpose. But I also want to check if any random billing address is linked to the card. I want to create a test scenario in which a card number is linked to a billing address and later in my website I want to enter random data billing to address if the payment fails or not. Is there anything in stripe that would help me achieve this functionality. -
Django, how can open modal form with value using jquery?
I'm new at django and jquery, I have a data table in which in the last column I have created the bottom "edit" that give me the possibility to modify the value of the row data. But when I clcik on the bottom and open the html modal, all fields are empty, but I want that it give me the value of single items as stored. My Modal: <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="myModalLabel">Modifica Materia Prima</h4> </div> <form id="updateUser" action=""> <div class="modal-body"> <input class="form-control" id="form-id" type="hidden" name="formId"/> <label for="codice">codice</label> <input class="form-control" id="form-codice" type="text" name="formCodice"/> <label for="tipologia">tipologia</label> <input class="form-control" id="form-tipologia" type="text" name="formTipologia"/> <label for="sottocategoria">sottocategoria</label> <input class="form-control" id="form-sottocategoria" type="text" name="formSottocategoria" min=10 max=100/> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary" >Save changes</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </form> </div> </div> My Javascript $("form#updateUser").submit(function() { var idInput = $('input[name="formId"]').val().trim(); var codiceInput = $('input[name="formCodice"]').val().trim(); var tipologiaInput = $('input[name="formTipologia"]').val().trim(); var sottocategoriaInput = $('input[name="formSottocategoria"]').val().trim(); if (codiceInput && tipologiaInput && sottocategoriaInput) { // Create Ajax Call $.ajax({ url: '{% url "crud_ajax_update" %}', data: { 'id': idInput, 'codice': codiceInput, 'tipologia': tipologiaInput, 'sottocategoria': sottocategoriaInput }, dataType: 'json', success: function (data) { if … -
module 'django.contrib.messages.constants' has no attribute 'success'
The documentation of django says 'success' is a function of django.contrib.messages.constants but when I execute django.contrib.messages.constants.success ,error comes as module 'django.contrib.messages.constants' has no attribute 'success' Error AttributeError at /contact module 'django.contrib.messages.constants' has no attribute 'success' Request Method: POST Request URL: http://127.0.0.1:8000/contact Django Version: 3.0.5 Exception Type: AttributeError Exception Value: module 'django.contrib.messages.constants' has no attribute 'success' Exception Location: C:\Users\User\PycharmProjects\Django\Hello\home\views.py in contact, line 35 Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe Python Version: 3.8.0 Python Path: ['C:\Users\User\PycharmProjects\Django\Hello', 'C:\Users\User\AppData\Local\Programs\Python\Python38\python38.zip', 'C:\Users\User\AppData\Local\Programs\Python\Python38\DLLs', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python38', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\pyzmail-1.0.3-py3.8.egg', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\distribute-0.7.3-py3.8.egg', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\win32', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\win32\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\Pythonwin'] views.py from django.shortcuts import render, HttpResponse from datetime import datetime from home.models import Contact from django.contrib.messages import constants as messages def contact(request): if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') phn = request.POST.get('phn') desc = request.POST.get('desc') cont = Contact(name=name,email=email,phn=phn,desc= desc,date=datetime.today()) cont.save() messages.success(request, 'Your mesaage has been sent') return render(request, 'contact.html') models.py from django.db import models class Contact(models.Model): name = models.CharField(max_length=122) email = models.CharField(max_length=122) phn = models.CharField(max_length=13) desc = models.TextField() date = models.DateField() admin.py from django.contrib import admin from home.models import Contact # Register your models here. admin.site.register(Contact) settings.py """ Django settings for Hello project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their … -
Django html extends tags
This is my base.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> {% block content %}{% endblock content %} </body> </html> This is home_page where I am using the {% extends 'base.html' %} {% load static %} {% block content %} <div class="container"> <h1>{{ title }}</h1> <h1>Hello, world!</h1> <img src="{% static 'img/myImage.jpg' %}" class='img-fluid'> </div> {% if premium_content %} <div class="row"> <div class="col"> <h1>Premium</h1> {{ premium_content }} </div> {% endif %} </div> {% endblock content %} The here is my views.py where I have the home_page and before using the extends tag I could render this page properly def home_page(request): context = { "title":"Hello World We Working" } if request.user.is_authenticated: context["premium_content"] = 'Only premium users see this' return render(request, 'MainApp/home_page.html', context) The error message that I am getting is TemplateDoesNotExist at / Which I do not understand I even tried putting the two html files in the same directory but still I get the same error message -
Django Vote System - django-secretballot and django-vote both are falty for me, should I write voting system myself?
I would like to ask you for your help. I want to have some simple voting system on my django app. I googled it and I found two systems and some posts about not reinventing wheel and I am all for that :P First I tried to go with django-vote, it was updated two years ago. I setup it, added into apps, models, created function for it with user_id but I got error with "LazyObject". user_id from django-vote was expecting int, and not actual user name like it is in my app. So I went with django-secretballot next. But soon after adding it into middleware and apps I am getting error while I want to migrate: ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' And right now I am lost. Should I try to ask for help and try to fix any of those two applications or I should look for another one or try to write it myself since I need only basic functions? Which approach would be better? Thanks and Cheers! -
DJANGO_SETTINGS_MODULE
Regarding : django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have tried every possible solution that is out there on the web, but unfortunately without any luck so far. I have noticed however that Django is not appearing under 'File -> Settings -> Languages & Frameworks', although it seems I have installed it properly (I am able to retrieve Django version number 3.0.5 and when I run manage.py, I get a list of the available subcommands). Also 'os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Eric.settings')' is properly set in manage.py file. Still I am running into the above error whenever I try to run 'django-admin runserver' ! I was expecting to find Django in the Languages & Frameworks section, but it seems to be missing there. Is this OK or NOK ? Thanks -
IntegrityError (1452, 'Cannot add or update a child row: a foreign key constraint fails)
I'm using a custom user model (following this tutorial) and all works well. When I'm logged in with the admin user I created with createsuperuser in the /admin session I can add/remove/edit anything I want. When I'm logged in with some other user, to which I've given staff and admin powers, I get this error whenever I want to add something to the database: IntegrityError at /admin/users/user/13/change/ (or whichever action I'm doing) (1452, 'Cannot add or update a child row: a foreign key constraint fails (`NMS_database`.`django_admin_log`, CONSTRAINT `django_admin_log_user_id_c564eba6_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`))') [...]Exception Location: /home/me/python_ve/lib/python3.8/site-packages/MySQLdb/connections.py in query, line 239 This is my user model: class User(AbstractBaseUser): email = models.EmailField(verbose_name="email", unique=True, max_length=255) first_name = models.CharField(max_length=30, blank=True, null=True) surname = models.CharField(max_length=30, blank=True, null=True) additional = models.BooleanField(default=False) individual = models.BooleanField(default=True) active = models.BooleanField(default=True) #can they login? staff = models.BooleanField(default=False) #staff user non superuser admin = models.BooleanField(default=False) #superuser date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' # default identifier for that user which will used for logging in #email (USERNAME_FIELD in this case) and password are required by default REQUIRED_FIELDS = ['first_name', 'surname'] def __str__(self): return "%s %s" % (self.first_name, self.surname) def get_full_name(self): return self.first_name def has_perm(self, perm, obj=None): return self.admin def has_module_perms(self, app_label): … -
Django - printing variables in templates
I created an app called "jobs", basically I'd like to create new "jobs" from the admin console and be able to post it on the jobs.html page. I created the model and views but I think there is something wrong with the views that doesn't allow me to print the "jobs" on the html template. Can you please me if the error is in views.py? jobs/models.py from django.db import models # Create your models here. class post_job(models.Model): posizione= models.TextField(max_length=20) descrizione= models.TextField(max_length=20) requisiti= models.TextField(max_length=20) def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" return self.posizione jobs/admin.py from django.contrib import admin from .models import post_job # Register your models here. admin.site.register(post_job) jobs/views.py from django.shortcuts import render from .models import post_job # Create your views here. def viz_job(request): posizione = post_job.posizione print(posizione) return render(request,'jobs/jobs.html',{'posizione':posizione}) -
JSON value doesn't change inside ajax success callback function
I'm working on a django reddit clone project, just to improve my skills. I wanted to implement AJAX to it so the page doesn't refresh when someone upvotes. I made an API with django rest framework, which has upvoted and downvoted boolean values. However, when I try to change the upvoted value to false in my javascript, it doesn't work, but changing it to true when it's false works and updates the template. This is probably confusing so here is some code. class UpvoteAPIToggle(APIView): def get(self, request, id=None, format=None): post = Post.objects.get(id=id) all_post_upvotes = post.upvotes.all() all_post_downvotes = post.downvotes.all() profile = Profile.objects.get(user=self.request.user) upvoted = False downvoted = False if profile not in all_post_upvotes: post.upvotes.add(profile) downvoted = False if profile in all_post_downvotes: post.upvotes.remove(profile) upvoted = False downvoted = True else: post.downvotes.remove(profile) upvoted = True serializer = PostSerializer(all_post_upvotes, many=True, read_only=True) serialized_upvotes = serializers.serialize("json", all_post_upvotes) upvote_counter = 0 data = { "upvoted":upvoted, "downvoted": downvoted, "all_post_upvotes":serialized_upvotes, "upvote_counter":upvote_counter } return Response(data) this is the class based rest view. $.ajax({ url: upvoteUrl, data: {}, dataType: "json", success: (data)=>{ checkVote(data) } }) function checkVote(data){ if (data.upvoted){ data.upvote_counter--; data.upvoted = false }else{ data.upvote_counter++; data.upvoted = true $(".upvote-btn").css("color","orange"); $("#upvoteCounter").text(data.upvote_counter) } } Here is the jquery part from the template. It … -
Dealing with byte literals in Django unit tests
I have this line in my unit test: self.assertEqual(get_response.content, f'APIUserMiddleware User, {remote_user}, does not exists.') This fails with this output: AssertionError: "b'APIUserMiddleware: User, bad.gen, does not exists.'" != 'APIUserMiddleware User, bad.gen, does not exists.' How should I deal with the byte literal being returned from an API? -
Scrapy pipelines Django update item in database SQLite
In my Scrapy project connected with Django, I scrape pages with offerts for housing markets and save in database. In pipelines file I create unique hash_id for each item and with other data save in db. Each time I want to update db for new offerts (it works) but also for closed offerts (not displayed more on page) change status in db for 'not active'. How to do that when process_item works only for specific scrapped item? My idea was to collect all hash_id from db in list, check scrapped items if their hash_id are in. If yes, delete the hash_id from list. Then update remaining items status. But it doesn't work. My pipelines file: def hashed_list(): hashed_items_db = Offert.objects.filter(still_active = True) hashed_list=[item.hash_id for item in hashed_items_db] return hashed_list class ScraperPipeline(object): hashed_list = hashed_list() def create_hash(self, *args): ... return data def process_item(self, item, spider): ..... hash_id = self.create_hash(args) item['hash_id'] = hash_id if hash_id not in hashed_list: item.save() else: hashed_list.remove(hash_id) return item def close_spider(self, spider): for hash_item in hashed_list: obj =Offert.objects.get(hash_id=hash_item) obj.still_active = False obj.end_date = timezone.now() - timedelta(days=1) obj.save() return hashed_list How to do that? Is there any easy (??) way to update non scrapped items in db? -
Unique constraint failed - Integrity error - django
Can't find a solution for my probelm online. error message I am receiving regarding problem ----- IntegrityError at /add_user_address/ UNIQUE constraint failed: users_useraddress.user_id ------ all help greatly appreciated! views.py import re from django.urls import reverse from django.shortcuts import render, redirect, Http404, HttpResponseRedirect from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .forms import UserRegisterForm, UserAddressForm from .models import EmailConfirmed def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your registration has been successful! Please check your email to confirm account.') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) SHA1_RE = re.compile('^[a-f0-9]{40}$') def activation_view(request, activation_key): if SHA1_RE.search(activation_key): print("activation key is real") try: instance = EmailConfirmed.objects.get(activation_key=activation_key) except EmailConfirmed.DoesNotExist: instance = None messages.success(request, f'There was an error with your request.') return HttpResponseRedirect("/") if instance is not None and not instance.confirmed: page_message = "Confirmation successful, welcome to Fuisce! " instance.confirmed = True instance.activation_key = "Confirmed" instance.save() elif instance is not None and instance.confirmed: page_message = "Already Confirmed" else: page_message = "" context = {"page_message": page_message} return render(request, "users/activation_complete.html", context) else: raise Http404 @login_required def profile(request): return render(request, 'users/profile.html') **def add_user_address(request): print(request.GET) try: redirect = request.GET.get("redirect") except: redirect = None if … -
How to submit content then display output on same page in Django
I am working with a DJango project. On my homepage I just have a drop down menu and a text area. The user will select something in the drop down menu, input some text in the text area and then push a button. Right now the only way I know how to do this is by redirecting the user to another page and displaying all the data. I was hoping I could do this by putting all the content underneath the dropdown menu, text area, and button. I am using Django. home.html <form action="{% url 'parsed' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="sel1">Select Test:</label> <select class="form-control" name="selectedtest" id="sel1"> {% for test in test %} <option value="{{ test.name }}"">{{ test.name }}</option> {% endfor %} </select> </div> <div class="form-group"> <label>Paste Event JSON</label> <textarea class="form-control" name="jsontextarea" rows="20"></textarea> <div style="text-align:center"> </br> <input class="btn btn-primary" type="submit" value="Parse"> </div> </div> </form> I will be building a large chart full of rows that I would like to display under all of this. -
Create multi model and Use them in one template in django
Well, I want to create a portfolio project using django. In the Home page of the site the main part is there's some project list and also some review list. I want to Show them both in my homepage(same template). But the problem is, I created a model for the Project list and created a Listview for that and rendered that into the homepage template. Now I don't know how to create the same for my review list. Because if I do the same, then what should I put at the urls section? So is there any option to do so? I think the question is clear, if it's not, please ask in the comment. Thanks in Advance -
How to use get_queryset inside a listview
I am struggling to use a simple get_queryset inside a listview. The goal is simply to filter the sets associated to a given cruise. My models look like this: from django.db import models class Cruise(models.Model): name = models.CharField(max_length=50) start_date = models.CharField(max_length=50) end_date = models.CharField(max_length=50) team_leader = models.CharField(max_length=50) def __str__(self): return self.name class Set(models.Model): cruise = models.ForeignKey(Cruise, on_delete=models.CASCADE) set_number = models.IntegerField() start_depth = models.IntegerField() end_depth = models.IntegerField() my urls look like this: from django.urls import path from . views import (CruiseListView, CruiseUpdateView, SetListView) from . import views urlpatterns = [ ... path('cruise/list/', CruiseListView.as_view(), name='app-cruise_list'), path('cruise/update/<pk>/', CruiseUpdateView.as_view(), name='cruise-update'), path('set/list/', SetListView.as_view(), name='set_list'), ] and the problematic view look like this: class SetListView(ListView): model = Set template_name = 'app/set_list.html' context_object_name = 'sets' #queryset = Set.objects.filter(cruise_id=1) def get_queryset(self): cruise_id = self.request.Cruise.id return Set.objects.filter(cruise_id=self.kwargs['cruise_id']) How can I filter and obtain only the sets associated with a given cruise ? I am getting a KeyError for cruise_id. Thank you, -
Ordering django model field
I have a Django model like this: COMUNI = [ ('1', 'ANA'), ('2', 'BAB'), ('3', 'ABA'), ] class ComuneConsegna(models.Model): COMUNI = COMUNI comune = models.CharField( max_length=2, choices=COMUNI, default='1', ) def __str__(self): return '{}'.format(self.get_comune_display()) Is it possible to order the model ComuneConsegna by the name reported with the method get_comune_display? Thanks -
I have two models News and Comment. I want to get the number of comments that was written to each news using templatetags
class News(models.Model): title = models.CharField(max_length=200) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField() image = models.ImageField(upload_to='pics',blank=True,null=True) category = models.ForeignKey(Category,on_delete=models.CASCADE) class Comment(models.Model): news = models.ForeignKey(News,on_delete=models.CASCADE) message = models.TextField() user = models.ForeignKey(User,on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) -
MultiValueDictKeyError when uploading image in Django
I am getting this MultiValueDictKeyError when I try to update my profile. The exception value is profile_pic. I am using a custom user model and created the profile model separately for the profile image. enter image description here This is my views.py def profile_edit(request): if request.POST: request.user.refresh_from_db() u_form = AccountUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid and p_form.is_valid(): u_form.initial = { "email": request.POST['email'], "username": request.POST['username'], "first_name": request.POST['first_name'], "last_name": request.POST['last_name'] } p_form.initial = { "birth_date": request.POST['birth_date'], "profile_pic": request.FILES['profile_pic'] } u_form.save() p_form.save() context['success_message'] = "Profile Details Updated" else: u_form = AccountUpdateForm( initial={ "email": request.user.email, "username": request.user.username, "first_name": request.user.first_name, "last_name": request.user.last_name, } ) p_form = ProfileUpdateForm( initial={ "birth_date": request.user.profile.birth_date, "profile_pic": request.user.profile.profile_pic, } ) context = { 'u_form': u_form, 'p_form': p_form, } return render(request, "accounts/profile_edit.html", context) Models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) birth_date = models.DateField(null=True,blank=True) profile_pic = models.ImageField(upload_to='pimage/', default='pimage/default.png') def __str__(self): return f'{self.user.username} Profile' forms.py class AccountUpdateForm(forms.ModelForm): class Meta: model = Account fields = ('email', 'username', 'first_name', 'last_name') def clean_email(self): email = self.cleaned_data['email'] try: account = Account.objects.exclude(pk=self.instance.pk).get(email=email) except Account.DoesNotExist: return email raise forms.ValidationError('Email "%s" is already in use.' % account) def clean_username(self): username = self.cleaned_data['username'] try: account = Account.objects.exclude(pk=self.instance.pk).get(username=username) except Account.DoesNotExist: return username raise forms.ValidationError('Username "%s" is already in use.' % … -
django my cod dont working! Grafic picture
myAPP name catalog I have models in models.py: class Sale(models.Model): good = models.ForeignKey ("Good", help_text = 'Select good', on_delete = models.SET_NULL, null = True) quantitysales = models.IntegerField (default=1, help_text = 'Enter Qty') datesales = models.DateField (null = True, blank = True) storename = models.ForeignKey ("Store", help_text = 'Select store', on_delete = models.SET_NULL, null = True) views.py i have try to make one grafic picture for webpage def sales_filter(request): with connection.cursor() as cursor: cursor.execute(''' select datesales, alcohol, confections from catalog_Sale where datesales = %s, order by datesales; ''', ('2020-04-10',)) dt = np.array([ ( (x), float (y), float (z) ) for (x, y, z) in cursor ]) fig, ax = plt.subplots() tm = np.array(dt[:,0]) alcohol = np.array([ x for x in accumulate(dt[:,1]) ]) confections = np.array([ x for x in accumulate(dt[:,2]) ]) ax.plot(tm,alcohol) ax.plot(tm,confections) #Generate image grafic buf = io.BytesIO() fig.savefig(buf,format='PNG') return HttpResponse( buf.getvalue(), content_type='image/png') My cod have eror Exception Value: near ",": syntax error and i dont know if my cod its correct, i need help please!!! -
How to add rows to django database from python script running on Colab?
I have a python web scraping script which collects data from multiple websites by scraping. My website (built using django) shows the collected data to the users in a table. Right now what I am doing is: run the script on Google Colab everyday, download the data in csv format, delete old data from website, upload new data on it (I have a page to upload and process the csv to add data in django database). I want to do something like this: within the Python script, call a URL like: mysite.com/uploadRowFromPython?cell1=SomeData&cell2=SomeMoreData&cell3=SomeOtherData The problem is, this method will make too many requests to my site and it might crash. Is there a better way to upload data automatically? Maybe add multiple rows at once? If the script directly uploads data to the site, I can setup a cron job to make the whole process automatic, instead of me having to daily run the script, delete old records from django database, and upload new csv. -
'NoneType' object has no attribute in the form init
Gives me that error 'NoneType' object has no attribute 'tutor_courses', i am trying to get query set with courses where request.user is in the tutor field.I tried to make tutor field is null but it didn't work, how to fix that? models.py class Course(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=150, null=True, blank=True) description = models.TextField() image = models.ImageField(upload_to='courses/course_images',blank=True,null=True) cover = models.ImageField(upload_to='courses/course_covers',blank=True,null=True) tutor = models.ForeignKey(User,related_name='tutor_courses',on_delete=models.CASCADE) students = models.ForeignKey(User,related_name='course_students',blank=True,on_delete=models.CASCADE,null=True) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) category = models.ForeignKey(CourseCategories,on_delete=models.CASCADE) certificate = models.ImageField(upload_to='courses/course_certificates',blank=True,null=True) languages = LanguageField(blank=True) rank_score = models.FloatField(default=0.0) price = models.FloatField(default=0.0) discount_price = models.FloatField(blank=True, null=True) forms.py class SectionForm(forms.ModelForm): def get_tutor_courses(self): return self.user.tutor_courses course = forms.ModelChoiceField(queryset=Course.objects.all()) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(SectionForm, self).__init__(*args, **kwargs) if user is not None: tutor_courses = user.tutor_courses.all() self.fields['course'].queryset = tutor_courses if not tutor_courses: self.fields['course'].help_text = "You need to <b>create</b> a course to create sections in it" class Meta: model = CourseSections fields = ('title','course') views.py def add_section_to_course(request): section_form = SectionForm(**{'user': request.user}) if request.method == 'POST': section_form = SectionForm(request.POST,request.FILES) if section_form.is_valid(): new_section = section_form.save(commit=False) new_section.creator.add(request.user) new_section.save() return redirect(new_section.get_absolute_url()) else: section_form = SectionForm() return render(request,'courses/create_section.html',{'section_form':section_form})