Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM is looking for a column that I dont create never
Im trying to pull data from external databse with django. I used inspectdb command for get the models, that database have two tables, when I try to get data from the first table, it works...but when I try to get the data from second table throws the next error: 1054, "Unknown column 'hotel_reviews.id' in 'field list'" The column id dont exist and its correct, but why its looking for it? This is how i have the models: from django.db import models class HotelInfo(models.Model): country_area = models.CharField(max_length=45) hotel_id = models.CharField(primary_key=True, max_length=32) hotel_name = models.TextField(blank=True, null=True) hotel_url = models.TextField(blank=True, null=True) hotel_address = models.TextField(blank=True, null=True) review_score = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) review_qty = models.IntegerField(blank=True, null=True) clean = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) comf = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) loct = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) fclt = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) staff = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) vfm = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) wifi = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) class Meta: managed = False db_table = 'hotel_info' unique_together = (('hotel_id', 'country_area'),) verbose_name_plural = "hotels" class HotelReviews(models.Model): uuid = models.CharField(db_column='UUID', max_length=36, blank=True, null=True) # Field name made lowercase. hotel_id = models.CharField(max_length=32, blank=True, null=True) review_title = models.TextField(blank=True, null=True) review_url = models.TextField(blank=True, null=True) review_score = models.DecimalField(max_digits=5, decimal_places=2, blank=True, … -
how to extract zip data from response in django
I want to retrieve data from below url for my django project. city bike trip, I am trying to something like this. data = requests.get('https://s3.amazonaws.com/tripdata/JC-201708%20citibike-tripdata.csv.zip') what I am getting zipped data with some info, my task is to unzip that data and convert it into django model object I saw people using gzip middleware in this answer but not sure if this solves purpose here, -
mock Job interview for python-aws developer
i'm bhandishboy, i'm python developer i've basic experience in web application development using python as language, django as framework, mysql and sqlite3 for storage, django-rest framework for api's. so i can work on CRUD projects. i guess next step will be hosting. for hosting aws services is in market. by going through google, i believe in documentations for every new updates, their uses and future scope. at this point i know how to use boto3 library for aws services in python language but i don't have any hands-on experience on that. on basis of above short description about my self, can company offers me a job? if offers then what will be "the questions" for python-aws developer. if company offer's me a job, i'm capable for first technical round. think i cleared first technical round of job post like python-aws developer, now my question is, if their is an second interview round by client for python-aws developer then what will be "The Questions" by the client Panel? any guess ? suggest me!!. thank you for your time and suggestions!! -
Django look up foreign-key form field (Newbie Question)
This is a basic question, but for some reason I cannot seem to find a straight answer, neither in the docs, nor in this forum. I am sure there must be a simple answer, but then again, I am new to Django (I know Python and databases pretty well) Scenario: 2 classes connected with a foreign key: Order --(foreign key)--> Order-approver (approver pk, fullname, title, etc.). Approver to Order is one-to-many relationship In the order entry form, I want to be able to pick/enter the approver by the full name (Django should presumably translate it into the approver id behind the scene). Ideally, there should be a look up form so I can select an approver by the name from the list How do I do that? What am I missing? -
I wanna use other backend to authenticate my backend
I'm building an app server-side on Django. There is a Laravel server with the authentications of my user. I need authenticate my user with Laravel, because I dont want to make other db on Django with the same users. How can I customize the django to authenticate this way ? -
How can I send a file with python websockets?
I need to transfer a file to a server (Django Channels) via websockets. How can I implement this in Python? -
Django: How do you compare a QuerySet with fields on a ForeignKey objects property?
I am trying to query a model against a field on a foreignkey objects property. I have the following models: class Song(models.Model): name = models.CharField(max_length=20) limit = models.IntegerField() class Recording(models.Model): song = models.ForeignKey(Song, on_delete=models.CASCADE) status = models.CharField( max_length=1, choices=STATUS_CHOICES, default=OPEN ) I would like to query Songs that have Recordings with status OPEN with a count of more than 'limit' (the field on Song). Looking over the django aggregation docs I tried something along the lines of: # View get(self): songs_count = Count('recording', filter=Q(recording__status='O')) songs = Song.objects.annotate(songs_count=songs_count) results = songs.filter(songs_count__gt=< each song.limit... >) Can someone point the way on how to build such a query? I greatly appreciate any and all feedback. -
How to fetch a field class from a specific form in Django?
I'm trying to write a test for the username field and I want to use SimpleTestCase.assertFieldOutput(). The problem is that I cannot get the fieldclass from the field of my form: import django from django.test import TestCase class UserRegistrationTest(TestCase): """Tests for the user registration page.""" def test_username_field(self): data = {'username': 'павел25', 'password1': 'njkdpojv34', 'password2': 'njkdpojv34', 'email': 'pav294@mail.ru', 'first_name': 'Pavel', 'last_name': 'Shlepnev'} f = RegistrationForm(data) self.assertFieldOutput(f.fields['username'], {'pavel25': 'pavel25'}, {'павел25': ['Имя пользователя должно содержать только символы ASCII.']}) When I run the test it raises TypeError: 'UsernameField' object is not callable -
Why is context not passed in formview django get method? Django, python
Error in the browser 'NoneType' object is not callable context = super().get_context_data(**kwargs) … ▼ Local vars Variable Value __class__ <class 'orders.views.OrderAddView'> args () kwargs {'tag': 'fast'} request <WSGIRequest: GET '/orders/add/fast'> self <orders.views.OrderAddView object at 0x00000000056EA430> Why isn't context passed to get? if accept context as self.get_context_data (** kwargs) same error views.py class OrderAddView(FormView): template_name = 'orders/order_add.html' formOne = SimpleOrderAddForm() formTwo = FastOrderAddForm() def get(self, request, *args, **kwargs): self.formOne.prefix = 'one_form' self.formTwo.prefix = 'two_form' context = super().get_context_data(**kwargs) context.update({'formOne': self.formOne, 'formTwo': self.formTwo}) return self.render_to_response(self.template_name, {'context':context}) def post(self, request, *args, **kwargs): formOne = SimpleOrderAddForm(self.request.POST, prefix='one_form') formTwo = FastOrderAddForm(self.request.POST, prefix='two_form') if formOne.is_valid() and formTwo.is_valid(): return HttpResponseRedirect('orders_home') else: return self.form_invalid(formOne, formTwo, **kwargs) def form_invalid(self, formOne, formTwo, **kwargs): context = self.get_context_data() formOne.prefix = 'one_form' formTwo.prefix = 'two_form' context.update({'formOne': formOne, 'formTwo': formTwo}) return self.render_to_response(self.template_name, {'context':context}) -
Django - Textchoices and admin.site.register
I have a choice class TextChoices: class Category(models.TextChoices): vegetable = 'VEG', 'vegetable' fruit = 'FRT', 'fruit' carbs = 'CRB', 'carbs' fish = 'FSH', 'fish' meat = 'MT', 'meat' sweet = 'SWT', 'sweet' dairy = 'DRY', 'dairy' ready = 'RDY', 'ready' # def __str__(self): # return self.name def __str__(self): return self.choices Used in: class Fooditem(models.Model): name = models.CharField(max_length=200) # category = models.ManyToManyField(Category) category = models.CharField(max_length=3, choices=Category.choices, default=Category.vegetable) Now, I would like to make Category editable by admin: admin.site.register(Category) But I have the following error: File "PycharmProjects\Calories_New\Fityfeed\admin.py", line 14, in <module> admin.site.register(Category.choices) File "PycharmProjects\Calories_New\venv\lib\site-packages\django\contrib\admin\sites.py", line 106, in register if model._meta.abstract: AttributeError: 'tuple' object has no attribute '_meta' I am relatively new in Django and would appreciate your help, also in understanding how I can solve these problems myself (struggling with reference documentation) Many Thanks! D -
How to update multiple images in django?
I'm trying to develop a post feauture with multiple images related to it and I have encoutered some problems I can't solve. So, in my models.py I have a Post model and PostImages model with one to many relationship: class PostImages(models.Model): post_id = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_directory_path, null=True, blank=False) I upload multiple images like this: def addpost(request): if request.method == 'POST': form = CreatePostForm(request.POST) images = request.FILES.getlist('images') if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() for i in images: PostImages.objects.create( post_id = post, image = i, ) return redirect('index') else: return redirect('addpost') else: context = {'formpost': CreatePostForm} return render(request, 'addpost.html', context=context) addpost.html: <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ formpost.as_p }} <input required name="images" type="file" multiple> <input type="submit" value="Submit"> </form> And I can't figure out how to edit multiple images: I tried something like this in my views.py def update_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.user != post.author: return redirect('index') context = {} images = post.postimages_set.all() count = 0 for i in images: count += 1 imagesformset = formset_factory(UpdateImagesForm, extra=count) context['formset'] = imagesformset if request.method == 'POST': form = UpdatePostForm(request.POST, instance=post) formset = imagesformset(request.POST, request.FILES) if form.is_valid() and formset.is_valid(): form.save() for form in formset: if form.is_valid(): … -
What is the best authentication method in django rest framework?
I want my website authentication to be strong For that purpose I have found the following things Combination of Base authentication with CSRF validation for session based authentication JSON Web Token Authentication support for Django REST Framework Which one is better among them? Or is there any other better method out there -
How do I use a for loop to reuse a django form in a template
After struggling with this issue for a while, I am hoping someone here can point me in a more productive direction. I am trying to take an indeterminate number of variables in a database (obtained through a different template) and render them on a webpage, each variable with a simple data entry form, to be saved back to the database. Basically, it's a tracker for analysis. Say I want to track my daily sleep, running time, and calorie intake (the variables). I have those saved in a database as variables and want to call upon those variables and show them on a webpage with a daily entry form. I am using a "for" loop right now and it renders the way I want it to, with the variable name and the form, but it is only saving the last item in the variable list. How do I amend the code below such that when I hit the save button for each form rendeded, it saves the information for that variable (not just the last one rendered). Below is the code. Any and all help would be infinitely appreciated. Models... class Variable(models.Model): date_added = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(get_user_model(), default='', on_delete=models.CASCADE) # … -
django html canvas load a background image on canvas
i have a html canvas where the user saves canvas and the user can laod their saved drawings onto canvas My models are as follows class Drawing(models.Model): drawingJSONText = models.TextField(null=True) project = models.CharField(max_length=250) class image(models.Model): upload = models.ImageField() project = models.CharField(max_length=250) My load function is as follows it filter thedrawing model and displays on canvas based on project field.now i have another model where i have an image for each project saved. so i need to display the image of project filteres(only one image for each project) on background while laoding the points onto canvas. My view function to load the drawing.It def load(request): """ Function to load the drawing with drawingID if it exists.""" try: filterdata = Drawing.objects.filter(project=2) ids = filterdata.values_list('pk', flat=True) length = len(ids) print(list[ids]) print(length) drawingJSONData = dict() drawingJSONData = {'points': [], 'lines': []} for id_val in ids: drawingJSONData1 = json.loads(Drawing.objects.get(id=id_val).drawingJSONText) drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"] drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"] print(drawingJSONData) drawingJSONData = json.dumps(drawingJSONData) context = { "loadIntoJavascript": True, "JSONData": drawingJSONData } # Editing response headers and returning the same response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context)) return response My javascript file to load the image onto canvas // Checking if the drawing to be loaded exists if … -
nginx rtmp_module http version
I use nginx rtmp to set up streaming platform with Django. Nginx have setting on_publish, there I enter the address where to send the request when the broadcast started. The problem is nginx sends a request with HTTP/1.0, but Django accept requests with HTTP/1.1 What can I do? Can I write http_version for nginx somewhere, or how to make django accept a request with HTTP/1.0 Config nginx worker_processes 1; events { use kqueue; worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; server { listen 8080; server_name localhost; root path_to_root; location ~ ^/live/.+\.ts$ { # MPEG-TS segments can be cached upstream indefinitely expires max; } location ~ ^/live/[^/]+/index\.m3u8$ { # Don't cache live HLS manifests expires -1d; } location / { proxy_pass http://127.0.0.1:7000/; proxy_http_version 1.1; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } rtmp { server { listen 1935; application stream { live on; allow play all; on_publish http://127.0.0.1:7000/start_stream; on_publish_done http://127.0.0.1:7000/stop_stream; hls on; hls_path path_to_live; hls_nested on; hls_fragment_naming system; hls_datetime system; } } } Error in django: [12/Mar/2021 12:11:50] "POST /start_stream HTTP/1.1" 500 93963 It's request from postman, OK Forbidden: /start_stream [12/Mar/2021 12:12:02] "POST /start_stream HTTP/1.0" … -
Displaying recurring events in Django Calendar
I am new to Django and I am trying to design a calendar app that displays events. I am using the provided source code as the initial code for the calendar: https://github.com/sajib1066/django-eventcalender. While this code works fine, I am trying to implement occurrences to each event, so each event can repeat in a specific frequency defined by me. To do this i used "django-eventtools" (link:https://github.com/gregplaysguitar/django-eventtools/tree/391877dc654427cce1550ad62fd3537786dfed26). While I am able to already display each event on the calendar, i can't make it display everyday when it is already defined to repeat daily. To display each event, I am using a generic.ListView but I am guessing my issue is that I can't use my occurrence data in the context to be displayed. models.py: class Event(BaseEvent): # adicionar cliente user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200, unique=True) description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('calendarapp:event-detail', args=(self.id,)) @property def get_html_url(self): url = reverse('calendarapp:event-detail', args=(self.id,)) return f'<a href="{url}"> {self.title} </a>' class MyOccurrence(BaseOccurrence): title = models.CharField(max_length=50, unique=True, default='No Title') event = models.OneToOneField(Event, on_delete=models.CASCADE) def __str__(self): return self.title def create_event_occurence(sender, instance, created, **kwargs): if created: for event in Event.objects.all(): MyOccurrence.objects.get_or_create(title=instance.title, event=instance, start=instance.start_time, end=instance.end_time) post_save.connect(create_event_occurence, sender=Event) … -
Django doesn't add new tasks and buttons
I'm doing django todo app and Django delete(complete )button doesn't appear. Also, I can't add new tasks. Once buttons appeared but there was Reverse for 'completed' with arguments '('',)' not found. 1 pattern(s) tried: ['completed/(?P<todo_id>[0-9]+)$'] error. views.py: tasks = [] @login_required def index (request): tasks = NewTask.objects.all() if "tasks" not in request.session: request.session["tasks"] = [] if request.method == "POST": form = NewTaskForm(request.POST) if form.is_valid(): todo = form.cleaned_data["task"] return HttpResponseRedirect(reverse( "todo:index")) else: return render(request, "todo/index.html", { "form":form }) return render(request, "todo/index.html", { "tasks":tasks, "form":NewTaskForm(), }) def completed(request, todo_id): item = NewTask.objects.get(pk=todo_id) item.delete() messages.info(request, "item removed !!!") return HttpResponseRedirect('') index.html: <ul class="tasks"> {% for todo in tasks%} {% csrf_token %} <form class = "done" action="completed/{{task.id}}" method="post"> {% csrf_token %} <input type='submit'><i class="fas fa-check"></i> </form> {%endfor%} </ul> forms.py class NewTaskForm(ModelForm): class Meta(): model = NewTask fields = ['task'] models.py class NewTask(models.Model): task = models.CharField(max_length=10000) done = models.BooleanField(default=False) def __str__(self): return self.task -
Django - Datatables - Chained Dropdown List - Reset the last selected options when reloading to the page
I was inspired by this article to set up chained dropdown list How to Implement Dependent/Chained Dropdown List with Django. I created three chained dropdown list (named respectively id_division, id_section id_section) above a Datatable (https://datatables.net) named table : <div class="form-row" style="margin-left: 0" id="id-orga-form" data-divisions-url="{% url 'load_divisions' %}" data-sections-url="{% url 'load_sections' %}" data-cellules-url="{% url 'load_cellules' %}"> <span style="margin-right: 10px">Filtrer : </span> <div class="form-group col-md-2"> <label for="id_division">Division</label> <select name="Division" id="id_division" class="form-control-sm"></select> </div> <div class="form-group col-md-2"> <label for="id_section">Section</label> <select name="Section" id="id_section" class="form-control-sm"></select> </div> <div class="form-group col-md-2"> <label for="id_cellule">Cellule</label> <select name="Cellule" id="id_cellule" class="form-control-sm"></select> </div> </div> Each list is used to apply a filter on a specific column. This works perfectly. $('#id_division').change(function () { divisionId = $(this).val(); $("#id_section").html(''); // initialize an AJAX request pour SECTION $.ajax({ url: $("#id-orga-form").attr("data-sections-url"), // add the division id to the GET parameters data: { 'division': divisionId }, // replace the contents of the section input with the data success: function (data) { $("#id_section").html(data); } }); search_division = $.trim($('#id_division option:selected').text()); if ( divisionId === null || search_division === '---------') { table.column([7]).search('').draw(); } else { table.column([7]).search('"' + search_division + '"').draw(); } $("#id_section").trigger("change"); }); $("#id_section").change(function () { sectionId = $(this).val(); $("#id_cellule").html(''); // initialize an AJAX request pour CELLULE $.ajax({ url: $("#id-orga-form").attr("data-cellules-url"), // add … -
Python, Django: Merge respectively join multiple models with foreignkey
Good evening, I would like to ask if there's a possibility inside django (database-queries) to merge multiple models with one request. I'm not very good in sql but I think it's called join or merge there? models.py class ObjectA(models.Model): name = models.CharField(max_length=50) class ObjectB(models.Model): name = models.CharField(max_length=50) amount = models.IntegerField(default=0) object_a = models.ForeignKey(ObjectA, null=False, blank=False, on_delete=models.CASCADE) class ObjectC(models.Model): name = models.CharField(max_length=50) amount = models.IntegerField(default=0) object_b = models.ForeignKey(ObjectB, null=False, blank=False, on_delete=models.CASCADE) What I'm trying to achive... object_a | object_b_name | object_b_amount | object_c_name | object_c_amount a_01 | b_01 | 17 | c_01 | 42 a_01 | b_02 | 21 | c_02 | 0 a_02 | b_03 | 145 | c_02 | 29 a_03 | b_04 | 0 | c_02 | 31 a_03 | b_05 | 0 | c_04 | 102 a_04 | b_06 | 73 | c_09 | 54 Is something like this possible or is it a problem, that each class only contains the foreignkey to the "previous level"? Hoping someone has an answer!? Thanks to all of you and have a great weekend! -
Field is empty in database after self-written clean_field is called
I'm trying to secure that each email can only be used once, thus having the following clean method from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ValidationError class UserRegisterForm(UserCreationForm): email = forms.EmailField() . . . def clean_email(self): """ Check if that email already exists in the database """ email = self.cleaned_data["email"] if User.objects.filter(email=email).exists(): raise ValidationError("This email already exists") return email and all the checks works as intended. The issue is that after the user is created, the email field is empty. Even if I hardcode the returned-email i.e class UserRegisterForm(UserCreationForm): email = forms.EmailField() . . . def clean_email(self): email = self.cleaned_data["email"] if User.objects.filter(email=email).exists(): raise ValidationError("Der er allerede en bruger med den email") return "my_email@email.com" it is still empty in the database when the user is created. I have attached the view aswell below, if that could be it #views.py def register(request): if request.method=="POST": #post request form = UserRegisterForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Yey - success! Log in here ") return redirect("login") else: form = UserRegisterForm() return render(request,"users/register.html",context= {"form":form}) What am I missing here? -
Error compiling Dockerfile to install wikipedia-API in Python
I´m trying to compile my Docker but I found the error bellow in my Django project. I tried to include urllib3 and request in my dockerfile but the error is the same. It´s looks like some about temporary config/cache directory error, but I don´t know how can I fix it in my Django project. Matplotlib created a temporary config/cache directory at /tmp/matplotlib-njyb_ktv because the default path (/.config/matplotlib) is not a writable directory; it is highly recommended to set the MPLCONFIGDIR environment variable to a writable directory, in particular to speed up the import of Matplotlib and to better support multiprocessing. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 368, in execute self.check() File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 396, in check databases=databases, File "/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/usr/local/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 589, in … -
Django Rest Framework adds an extra word when do query
Im trying to get data from a server. This server have a bbdd with name Schools and there inside have two tables called student and teacher, they have a one to many relationship. I only have read permissions so i cant do migrations. Im working with Django and DjangoRestFramework It seems its all ok but when I do a call to the view I have this error: 1146, "Table 'Schools.api_teacher' doesn't exist obviously does not exist that table, the correct would be Schools.teacher Is there a way to correct this? -
How do I add my html navbar into another html file in django
I am still very new to Django and I want to add the HTML for a navigation bar and its respective CSS into my base HTML file. Here is what I did up till now: in app/base.html: {% extends "BritIntlSchl/navbar.html" %} {% load static %} <!DOCTYPE html> <html> <head> <title>page title</title> <link href="{% static 'appname\stylebase.css' %}" rel="stylesheet"> <link href="{% static 'appname\navbarstyles.css'}" rel="stylesheet" %}"> {% block head-content %}{% endblock head-content %} </head> {% block nav%}{% endblock nav %} {% block content1 %}{% endblock content1 %} </body> </html> and in app/navbar.html: {% block nav%} <div class="wrap">...</div> {% endblock nav%} I am pretty much lost here. I am sure that putting{% block nav%} around the nav bar does nothing. How do you suggest I go about this? I'm using Django 2.1. -
How to create product based file
I have a shop that based on Oscar framework. One of my product is a service that based on a file that the customer upload. The customer choose the service, upload a file, there are some calculations and a price that based on the file the customer uploaded. Any idea how to do it with Oscar? Until now, I did it with a regular form. Or shall I need to create a new product class and new view? -
Field 'id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at
there I am using a queryset in Django- whenever I run the server, it gives an error. I don't know whether its an issue with my models.py or .. I tried looking up this DeferredAttribute object on Google, but I didn't really see any answer that works for me Field 'id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at 0x0000021CBFAE7940>. models.py from django.db import models from django.utils import timezone class User(models.Model): name = models.CharField(max_length=30) email = models.CharField(max_length=50) password = models.CharField(max_length=30) class Meta: db_table = "managestore_user" class Data_source(models.Model): name = models.CharField(max_length=30) class Meta: db_table = "managestore_data_source" class Data(models.Model): customer_idd = models.CharField(max_length=30) customer_name = models.CharField(max_length=30) gender = models.CharField(max_length=30) country = models.TextField(max_length=30) city = models.TextField(max_length=50) state = models.TextField(max_length=50) category = models.TextField(max_length=100) sub_category = models.TextField(max_length=100) product_name = models.TextField(max_length=100) sales = models.FloatField() quantity = models.IntegerField() discount = models.FloatField() profit = models.FloatField() class Meta: db_table = "managestore_data" class Manage_store(models.Model): data_source_name = models.TextField(max_length=30) file_name = models.TextField(max_length=30) execution_time = models.TextField(max_length=30) number_of_records = models.IntegerField() data_source = models.ForeignKey(Data_source, on_delete=models.CASCADE) data = models.ForeignKey(Data, on_delete=models.CASCADE) created = models.DateTimeField(editable=False) modified = models.DateTimeField() def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() self.modified = timezone.now() return super(Manage_store, self).save(*args, **kwargs) class Meta: db_table = "managestore_manage_store" view.py def upload(request): # if forms.is_valid(): # answer = …