Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems with the Django Admin. Doesn't show Users section
Can anyone tell me why is it that I don't see the "Users" section within Authentication and Authorization? If you need more code, please let me know. I honestly don't know what happened, always in all my Django projects, when I create the Superuser and enter the url '/ admin', there is the Users section. I don't know what could be wrong. I appreciate your help ♥ models.py from django.db import models from django.db.models import Count from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.dispatch import receiver terminal log [11/Jul/2021 02:18:44] "GET / HTTP/1.1" 200 6606 [11/Jul/2021 02:18:48] "GET /admin/ HTTP/1.1" 302 0 [11/Jul/2021 02:18:49] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 2267 [11/Jul/2021 02:18:57] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 [11/Jul/2021 02:18:57] "GET /admin/ HTTP/1.1" 200 5483 [11/Jul/2021 02:19:13] "GET /admin/auth/ HTTP/1.1" 200 2910 admin.py from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from cerveceria.models import * -
How do I create a bidding system using django?
I am currently interested in making a website that functions similar to freelancer.com. In the platform, I want to have two types of users: employers and employees. When an employer posts a job using a django model form, for example, someone looking for article writing services, it becomes visible to employees to bid. When the employer picks one employee, the job becomes invisible to other employees. It becomes a private communication between the employer and the employee. I am stuck in creating the bidding system. I don't know which django (python) function to use for bidding to display all the functions I have stated. I can so far create a job django model and employer forms to post the jobs to the available list of jobs on the website. I don't know what to do next for employees to start bidding on the job. I also want to know the python function I can use so that when the order is marked completed, the employee can no longer upload new files. Please advise. -
How to reconcile shared applabel in two third party apps in django?
I have a large django project I am working on, that is largely based around the wagtail CMS. I recently added the django-wiki app to my project, and ran into issues running makemigrations, getting the error: "Application labels aren't unique, duplicates: sites " It seems both wagtail and django-wiki have apps and applables called 'sites', which is causing a conflict. Given that these apps are not my apps, renaming them as though they were would seem like a bad approach, causing issues whenever I were to upgrade. What is the correct approach to deal with this problem without breaking the packages? -
Custom User Model with multiple Unique id - Django RestFramework
Hi StackOverFlow buddies, I have created a custom User model for my project and would like to register the Users with Restframework. I want Custom User model to have 2 unique fields together, for which I followed "Official doc" for unique_together property. It seems to be only taking only 1 field (ie email for my case), as a unique one. Relevant piece my code until this point looks like this: PS: Let me know if more info is required. models.py class MasterUser(AbstractBaseUser): email = models.EmailField(verbose_name='email address',max_length=255,unique=True,) firstname = models.CharField(max_length=100,blank=True) contact = models.CharField(max_length=100, blank=True) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['firstname'] class Meta: unique_together = (('email', 'contact'),) serializer.py password2 = serializers.CharField(style={'input_type': 'password'}, write_only= True) class Meta: model = MasterUser fields = ('firstname', 'password', 'password2', 'email','contact') extra_kwargs = { 'password': {'write_only': True}, } def save(self): account = MasterUser( email = self.validated_data['email'], firstname = self.validated_data['firstname'], contact = self.validated_data['contact'], ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Password doesnt matches'}) account.set_password(password) account.save() return account views.py @api_view(['POST']) def registration_view(request): if request.method == "POST": serializer = RegisterUserSerializer(data= request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = "Successfully registered new user!" else: data = serializer.errors return Response(data) Where … -
Errno 111 Connection refused Django REST on CPanel
I'm using gmail smtp, and I get this error: [Errno 111] Connection refused I'm getting this on cpanel shared hosting, but it's working perfectly fine on local. Here's my Django configuration: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = config("EMAIL_HOST") EMAIL_PORT = 587 EMAIL_HOST_USER = config("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = config("EMAIL_HOST_PASSWORD") EMAIL_FROM = config("EMAIL_FROM") DEFAULT_FROM_EMAIL = 'email@gmail.com' SERVER_EMAIL = 'email@gmail.com' EMAIL_BCC = "" EMAIL_USE_SSL = False I contacted my WHM and told them to disable smtp restrictions. Their firewall is also not blocking gmail's smtp and the required ports are also open. Please help me. -
Django JQuery autocomplete not working - nothing showing up, but API URL works
I have tried to implement autocomplete exactly as this tutorial shows: https://www.youtube.com/watch?v=-oLVZp1NQVE Here is the tutorial code, which is very similar to what I have here: https://github.com/akjasim/cb_dj_autocomplete However, it is not working for me. The API url works, but nothing populates in the field, i.e. there is no autocomplete that shows up. What could I be doing wrong? Here is the jquery: <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function () { $("#product").autocomplete({ source: '{% url 'autocomplete' %}', minLength: 2 }); }); </script> Here is the html: <title>Autocomplete</title> </head> <body> <form> <label for="product">Product</label> <input type="text" name="product" id="product"> </form> Here is the views: def autocomplete(request): if 'term' in request.GET: qs = Model.objects.filter(title__icontains=request.GET.get('term')) titles = list() for product in qs: titles.append(product.title) # titles = [product.title for product in qs] return JsonResponse(titles, safe=False) return render(request, 'file_for_viewing.html') Then here is the URL: path('autocomplete',views.autocomplete, name='autocomplete'), -
Issue connecting to secure websocket using Django/Nginx/Daphne
Having an issue using secure websocket (wss) with django, Nginx, Gunicorn, and daphne. My site is hosted through cloudflare which provides the SSL/TLS certificate. I'm using a linux socket in /run/daphne/daphne.sock, where I gave the user 'ubuntu' ownership of the daphne folder. The websockets work fine locally when it is not secured. When I tried hosting on my EC2 instance, I get the error- sockets.js:16 WebSocket connection to 'wss://www.mywebsite.com/ws/sheet/FPIXX8/' failed: Then it keeps trying to reconnect and fail again. It never sets up an initial connection since I don't get a ping. Here are a few relevant files and snippets of code- settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', # asgi_redis.RedisChannelLayer ? 'CONFIG': { 'hosts': [('localhost', 6379)], }, } } I think there may be an issue with the 'hosts' but I haven't been able to figure out through tutorials/googling, nor am I sure exactly what it does besides set a port. Since I'm using sockets, I imagine this would need to be different (or maybe it's ignored?) in deployment. Routing.py (in main project dir) from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import app.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( … -
Executing a multitable SQL query using a Django QuerySet
I'm working in a Django project and I would like to know how a data like that SELECT cities.name, states.name, countries.name FROM cities JOIN states ON states.id = cities.state_id LEFT OUTER JOIN countries ON countries.id = states.country_id WHERE cities.name = 'Guadalajara'; could be retrieved using the Django ORM (I mean using a model's query set and its filters). I'm not very experienced using ORMs and I'm much better in SQL. But I have to create similar queries in Django. What is the best way to do it? -
How to dynamically filter with get_queryset on one of many queries based on if-logic using gt (greater than), lt
I have 3 dropdown boxes that allow the user to pass a parameter (1), operator (2), criteria (3) e.g "price (1) greater (2) than 200 day simple moving average (3)". I am overriding the get_queryset function from my views.py file and testing with user entering the query above into the dropdown boxes. The outcome I am seeking is simply to be able to catch all of the possible combinations in if-statements and only return the relevant filtered query that matches the 3 conditions selected. In my code below the intial queryset = TableData.objects.all() remains as the query set even if I do reach the other filtering conditions in my if-statement. def get_queryset(self, *args, **kwargs): #global queryset #tried making this global but it didn't work queryset = TableData.objects.all() req = self.request.GET ajax_requests = req.getlist('filterList[]') for req in ajax_requests: parameter = "" operator = "" criteria = "" yourdict = json.loads(req) filter = yourdict[0] parameter = filter['parameter'] operator = filter['operator'] criteria = filter['criteria'] if parameter == 'priceAnchor': # The user selected to compare price as the first option if operator == 'ltOption': # The user wants to see price less than a third attribute if criteria == 'sma200Criteria': #TableData.objects.filter(price__lt=F('ma200')) queryset = TableData.objects.filter(volume__gt=100000000) … -
'powershell.exe' is not recognized as an internal or external command, operable program or batch file
I am using Windows 10, and Windows Powershell as command terminal. I just started to learn Django framework and being trying to setup my env as 1st time practice. This is my location: PS C:\Users\MyUsername\Desktop\cfeproj> This was successful: python -m pipenv install However, when I run : pipenv shell PS C:\Users\LENOVO\desktop\proj> pipenv shell Launching subshell in virtual environment... 'powershell.exe' is not recognized as an internal or external command, operable program or batch file. Please help me ho to configure this problem. I'm basically very new and still learning. Would be so appreciate if somebody can help me out here. =D -
Save a file from requests using django filesystem
I'm currently trying to save a file via requests, it's rather large, so I'm instead streaming it. I'm unsure how to specifically do this, as I keep getting different errors. This is what I have so far. def download_file(url, matte_upload_path, matte_servers, job_name, count): local_filename = url.split('/')[-1] url = "%s/static/downloads/%s_matte/%s/%s" % (matte_servers[0], job_name, count, local_filename) with requests.get(url, stream=True) as r: r.raise_for_status() fs = FileSystemStorage(location=matte_upload_path) print(matte_upload_path, 'matte path upload') with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk) fs.save(local_filename, f) return local_filename but it returns io.UnsupportedOperation: read I'm basically trying to have requests save it to the specific location via django, any help would be appreciated. -
Why do I get "AttributeError: 'Template' object has no attribute 'add_description'" error when deploy with Zappa?
So I'm trying to deploy my Django project with zappa. I've installed, and init-ed successfully and now trying to deploy. However, after zappa deploy, I get the following error: AttributeError: 'Template' object has no attribute 'add_description'.What do you think is the problem? Full error message is: Traceback (most recent call last): File "c:\users\user\envs\synergy\lib\site-packages\zappa\cli.py", line 3422, in handle sys.exit(cli.handle()) File "c:\users\user\envs\synergy\lib\site-packages\zappa\cli.py", line 588, in handle self.dispatch_command(self.command, stage) File "c:\users\user\envs\synergy\lib\site-packages\zappa\cli.py", line 630, in dispatch_command self.deploy(self.vargs["zip"], self.vargs["docker_image_uri"]) File "c:\users\user\envs\synergy\lib\site-packages\zappa\cli.py", line 960, in deploy endpoint_configuration=self.endpoint_configuration, File "c:\users\user\envs\synergy\lib\site-packages\zappa\core.py", line 2417, in create_stack_template self.cf_template.add_description("Automatically generated with Zappa") AttributeError: 'Template' object has no attribute 'add_description' -
how to create a file dynamically with OCR result from an image model
i created two apps in django one to upload a file and process it and one to preform OCR and create a pdf file from the processed image. so i have two models one for images and another for files, when i upload an image it goes through the processing pipeline then automatically the file field in the File model is populated with the result. When i m working with the admin panel or with DRF api root it is working fine, but when i use POSTMAN or react Native front end i get internal server error and the image is uploaded but no file is created. I m still learning django and backend concepts so i don't even know where to look for the issue: here are my models class Uploads(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title=models.CharField(max_length=100,default='none') image=models.ImageField(upload_to='media',unique=True) created_at = models.DateTimeField(auto_now_add=True) super(Uploads, self).save(*args, **kwargs) if self.id : File.objects.create( file=(ContentFile(Create_Pdf(self.image),name='file.txt') )) class File(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) label=models.CharField(max_length=100, default='none') title=models.CharField(max_length=200,default='test') file=models.FileField(upload_to='files') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) import PIL.Image pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' def Create_Pdf(image): text=pytesseract.image_to_string(PIL.Image.open(image)) return(text) -
Docker build error Could not find a version that satisfies the requirement Django
I'm just learning Docker and working with django from last 1 year. Today I try to work with docker and getting this error. ERROR: Could not find a version that satisfies the requirement Django<3.2.2 I'm familiar with this error. But with docker i don't know how to solve this. Dockerfile Configuration: FROM python:3.9-alpine ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user USER user requirements.txt Django >=3.2.5,<3.2.2 djangorestframework>=3.12.4,<3.9.0 see the error message image here can anyone help me how to fixed this ? -
Django is not updating my database after submitting my form
I have created a model and a form, both are working correctly, and I have added data to the database using the admin module models.py class Client(models.Model): firstname = models.CharField(blank=True, max_length=30) lastname = models.CharField(blank=True, max_length=15) company = models.ForeignKey(Company, on_delete=models.CASCADE, default="company") position = models.CharField(blank=True, max_length=15) country = CountryField(blank_label='(select country)') email = models.EmailField(blank=True, max_length=100, default="this_is@n_example.com") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) phone = PhoneField(default="(XX)-XXX-XXX") def __str__(self): return f'{self.firstname}' forms.py class ClientForm(forms.ModelForm): class Meta: model = Client fields = ('firstname', 'lastname',"position",'country','email','phone') views.py @login_required def add_client(request): if request.method == "POST": client_form = ClientForm(instance=request.user, data=request.POST) if client_form.is_valid(): client_form.save() messages.success(request, 'You have successfully added a client') else: messages.success(request, "Error Updating your form") else: client_form = ClientForm(instance=request.user) return render(request, "account/add_client.html", {'client_form':client_form}) add_client.html {% extends "base.html" %} {% block title %}Client Information {% endblock %} {% block content %} <h1> Client Form</h1> <p>Please use the form below to add a new client to the database:</p> <form method="post" enctype="multipart/form-data"> {{ client_form.as_p }} {% csrf_token %} <p><input type="submit" value="Save changes"></p> </form> {% endblock %} Everything seems to be working fine, I can submit data in the website and I get a message stating that the the submission when fine, however, when I check the admin website and inspect the database, … -
Django Foreign Key Related Objects Not Saving Changes, Cannot Edit
I have two models, Movie and Review. Review has a foreign key field related to Movie. I have been trying to edit the Review objects associated with an instance of Movie. models.py class Movie(models.Model): title = models.CharField(max_length=160) class Review(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='reviews') author = models.CharField(max_length=150) active = models.BooleanField(default=True) views.py # Create and save movie object movie = Movie(title="Nightcrawler") movie.save() # Create and save two review objects review1 = Review(movie=movie, author="John", active=True) review2 = Review(movie=movie, author="Rob", active=False) review1.save() review2.save() print("Before: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.") active_reviews = movie.reviews.filter(active=True) print("There are " + str(len(active_reviews)) + " active reviews.") movie.reviews.set(active_reviews) movie.reviews.first().author = "Abby" # Try and save both objects just for good measure. # Not sure if it is necessary to do this. Does not # seem to work anyway movie.reviews.first().save() movie.save() print("After: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.") print("Author of the first review is: " + str(movie.reviews.first().author)) The output of the views.py code is as follows: Before: Nightcrawler has 2 reviews. There are 1 active reviews. After: Nightcrawler has 2 reviews. Author of the first review is: John I want and expected the changes made to movies.reviews … -
Django is not picking CSS file
Django is not picking CSS file from static folder, though its picking image file in static folder. here is my Django structure rootapp -settings.py -urls.py -wsgi.py app1 -views.py app2 -views.py template -app1home -app2home -base static -logo.png -style.css urls.py from django.views.static import serve urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^media/(?P<path>.*)$', serve, kwargs={'document_root': settings.MEDIA_ROOT}), re_path(r'^static/(?P<path>.*)$', serve, kwargs={'document_root': settings.STATIC_ROOT}) ] In base.html.I have {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> It is picking logo as follows in the base file <img src="{% static "logo.png" %}" alt="logo"></a> <h1>Disease Diagnosis via AI</h1> But not picking style.css file. CSS file looks like h1{ margin-top: 10px; color: red; } Settings file MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Also, media paths are working -
Django template: two different font sizes on same line
I'd like to be able to render two different font sizes on the same line using a Django template. Here's my code: <div> <h5>Details</h5> </div> <div> <h6>Creator By:</h6> {{ order.creator }} </div> <div> <h6>Category:</h6> {{ order.category }} </div> This is rendering as follows: Details Created By: Janice Category: Automotive ############################################# Notice that the variables are skipping to a new line. I would like to render these as follows (on the same line): Details Created By: Janice Category: Automotive Is this just a simple mistake I've made with the HTML? Or, is there some nuance I'm missing with the Django form? Thank you! -
How to get the related field of a related field in Django REST Framework serializers?
Imagine having three Django Models: class A: Susu = models.CharField() # props... class B: a = models.ForeignKey(A) Bar = models.CharField() # props... class C: b = models.ForeignKey(B) c_prop # props... I'd like to write a serializer for C objects, such that they are represented as { "c_prop": "Foo", "b" : { "Bar": "Agu" }, "a" : { "Susu", "Jaja" } } i.e. the foreign key of the B class is representated at the same level of nesting as the B object (instead of "within" B) I have these serializers: class ASerializer(serializers.ModelSerializer): class Meta: model = A fields = ("Susu", ) class BSerializer(serializers.ModelSerializer): class Meta: model = B fields = ("a", ) class CSerializer(serializers.ModelSerializer): b = BSerializer class Meta: model = C fields = ('c_prop', 'b', 'a', ) # <-- How to get the 'a' here (not just the PK of 'a' but the nested object representation? -
Django authentication/user create functions
I'm trying to start a project in Django, where users can register on my site and subsequently login/logout when they visit it. I have found a template for a user creation view, that looks like this: from django.views.generic import CreateView from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login class CreateUserView(CreateView): template_name = 'register.html' form_class = UserCreationForm success_url = '/' def form_valid(self, form): valid = super(CreateUserView, self).form_valid(form) username, password = ( form.cleaned_data.get('username'), form.cleaned_data.get('password1') ) new_user = authenticate(username=username, password=password) login(self.request, new_user) return valid Now, I'm wondering why a call to authenticate with a non-existing username should create a new user. I'm trying to find any documentation for the imported functions authenticate and login, however, I can only find documentation for the User-model, AnonymousUser object, Permission-model, Group-model, some authentication backends and signals/validators, but I don't find any documentation for (standalone) functions authenticate and login. Can someone provide me the with a link to the relevant documentation or at least confirm that the way as they are used above is (still?) correct? -
Put the value of Not null in a field using Alterfield
In my Django project, I first added new fields to the project and set their null value to true, and then I wanted to set the Not null value for those fields via AlterField, but I was unable to do so. In this project, I manually created two migrations for these changes. 0002_edit_model: from django.db import migrations,models def excavating_information(apps, schema_editor): Person = apps.get_model('people', 'Person') #get data from fullname field full_name = [i.split(';') for i in Person.objects.values_list('fullname', flat=True)] full_name_finall = [f for i in full_name for f in i] #get data from information field information_field = [i.split(';') for i in Person.objects.values_list('information', flat=True)] information_field_final = [f for i in information_field for f in i] #Extract data from fullname first_name = [k[11:] for k in full_name_finall if k[1] == 'i'] last_name = [k[10:] for k in full_name_finall if k[1] == 'a'] #Extract data from information id_code = [k[8:] for k in information_field_final if k[1] == 'd'] born_in = [k[8:] for k in information_field_final if k[1] == 'o'] bith_year = [k[11:] for k in information_field_final if k[1] == 'i'] #final step for person,f, l, i, b, bi in zip(Person.objects.all(),first_name, last_name, id_code, born_in, bith_year): #update fields in person model person.objects.update(first_name=f, last_name=l, id_code=i, born_in=b, birth_year=bi) class … -
Optimizing Django with prefetch and filters in large table
I had a database in php/html using MySQL and am transferring this to a Django project. I have all the functionalities working, but loading a table of the data I want is immensely slow because of the relations with other tables. After searching for days I know that I probably have to use a model.Manager to use prefetch_all. However, I am not stuck on how to call this into my template. I have the following models(simplified): class OrganisationManager(models.Manager): def get_queryset_director(self): person_query = Position.objects.select_related('person').filter(position_current=True, position_type="director" ) return super().get_queryset().prefetch_related(Prefetch('position_set', queryset=person_query, to_attr="position_list")) def get_queryset_president(self): person_query = Position.objects.select_related('person').filter(position_current=True, position_type="president" ) return super().get_queryset().prefetch_related(Prefetch('position_set', queryset=person_query, to_attr="position_list")) class Person(models.Model): full_name = models.CharField(max_length=255, blank=True, null=True) country = models.ForeignKey(Country, models.CASCADE, blank=True, null=True) birth_date = models.DateField(blank=True, null=True) class Organisation(models.Model): organisation_name = models.CharField(max_length=255, blank=True, null=True) positions = models.ManyToManyField(Person, through='Position') # positions are dynamic, even though there should only be only one director and president at each given time, a onetoone model wouldn't work in this scenario objects = OrganisationManager() # The following defs are currently used to show the names and start dates of the director and president in the detailview and listview def director(self): return self.position_set.filter(position_current=True, position_type="director").last() def president(self): return self.position_set.filter(position_current=True, position_type="P").last() class Position(models.Model): POSITION_TYPES = ( ('president','President'), ('director','Director'), ) … -
Displaying javascript style alert after form submit in Django
I am creating a simple application in Django. I have a form on a page and after the form is submitted, I want to redirect the user to a new page and display a JavaScript alert like this. How would I go about doing this? My code is down bellow. This is the function that stores the form data and redirects to a new page, the new page only has simple html on it. def donate(request): if request.method == "POST": title = request.POST['donationtitle'] phonenumber = request.POST['phonenumber'] category = request.POST['category'] quantity = request.POST['quantity'] location = request.POST['location'] description = request.POST['description'] # New part. Update donor's stats. UserDetail.objects.filter(user=request.user).update(donations=F('donations') + 1) UserDetail.objects.filter(user=request.user).update(points=F('points') + (quantity * 2)) return render(request, 'dashboard.html', ) return render(request,'donate.html') I have done lot's of research but I can not find a logical solution to my problem. Past questions have asked me to use Django messages, which is something I don't want to use. Thank you to everyone who helps! -
Django App - I have a list of students which I upload within the app, how can I connect the student list with login so they only create new password
from django.shortcuts import render from .forms import csvForm from .models import csvList import csv from portal.models import Studentlist Create your views here. def upload_file_view(request): form = csvForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = csvForm() obj = csvList.objects.get(activated=False) with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i==0: pass else: print(row) #studID = row[0] middlename = row[1] #User.objects.get(username=row[1]) gender = row[2].capitalize firstname = row[3] #User.objects.get(username=row[3]) tPeriod = row[4] unitNum = row[5] teamid = row[6] Studentlist.objects.create( id = int(row[0]), surname = middlename, title = gender, name = firstname, teachPeriod = tPeriod, unitCode = unitNum, teamId = teamid ) obj.activated = True obj.save() return render(request, 'home.html', {'form': form}) -
unexpected keyword argument
enter code here class Client(models.Model): enter code here name = models.CharField(max_length=100, verbose_name="Client name") enter code here description = models.TextField(verbose_name="Client say") enter code here image = models.TextField(upload_to="clients", default="default.png") enter code here def __str__(self): enter code here return self.name i'm getting a TypeError: init() got an unexpected keyword argument 'upload_to'