Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to CreateView/UpdateView using foreign key in Nested model
Was able to perform CRUD on Branch. However I am stuck in create/update/delete for Feature.. Also when i move to Testcase CRUD, what steps do i need to do.? Please help.. Please Let me know if u need more info regarding this. ....... PS: I am new to django (2 weeks in.. enjoying it :-)). Model: class Branch(models.Model): """Model representing a Branches""" name = models.CharField(max_length=200, db_index=True, unique=True) summary = models.CharField(max_length=200, db_index=True) def __str__(self): """String for representing the Model object.""" return self.name def get_absolute_url(self): """Returns the url to access a particular branch instance.""" return reverse('branch-detail', args=[str(self.id)]) class Feature(models.Model): """Model representing a Feature""" branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True, related_name='features') name = models.CharField(max_length=200, db_index=True, unique=True) def __str__(self): """String for representing the Model object.""" return self.name def get_absolute_url(self): """Returns the url to access a particular feature instance.""" return reverse('feature-detail', args=[self.branch, str(self.id)]) class Testcase(models.Model): """Model representing a Testcase""" feature = models.ForeignKey(Feature, on_delete=models.SET_NULL, null=True, related_name='testcases') name = models.CharField(max_length=200) def __str__(self): """String for representing the Model object.""" return self.name def get_absolute_url(self): """Returns the url to access a detail record for this testcase.""" return reverse('testcase-detail', args=[self.feature.branch, self.feature, str(self.id)]) View: class BranchCreate(CreateView): model = Branch fields = '__all__' success_url = reverse_lazy('index') class BranchUpdate(UpdateView): model = Branch fields = ['name', … -
Django web app Docker - unable to coonect
I am new on Django and Docker and I have a problem to enter site localhost:8000. I built django app and it is working on my local server but I'd like to dockerize my app. So I created two files: Dockerfile : ROM python:3.6.7-alpine ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD ./ /code/ CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] and docker-compose.yml version: '3' services: web: build: . command: python mysite/manage.py runserver 8000 ports: - "8000:8000" My next steps: docker built --tag django_docker:latest . docker run django_docker It's open server, but when I want to open lokalhost:8000 from my browser I can't because of "Unable to connect" Where is my fault? I More about django app : it's project from book Python Crash Course : Learning_log. I'd like to build an image and push it to hub docker, but I am stuck. Thanks for help! -
Django Create Temporary File for Download
I have a model named 'Report Data'. I have a form which will get 'report_name' and will perform a operation. This operation basically loops through objects, every object returned has a file field having '.docx' file, this function will merge all these files into one docx file. After this 'convert' method will convert 'docx' to 'pdf'. I am able to perform this workflow but I need to create a temporary file instead of real files in media directory. My class based view is below class FilesListView(LoginRequiredMixin,ListView): model = ReportData template_name = 'report/myfiles.html' context_object_name = 'reportdata' def get_queryset(self): return ReportData.objects.filter(preparedby=self.request.user).order_by('-date_created') def post(self,request,*args,**kwargs): filtervalue = request.POST.get("report_name","") reportsforPDF = ReportData.objects.filter(reportname=filtervalue) reporturl = settings.MEDIA_ROOT[0:-6] master = Document(reporturl + reportsforPDF.first().document.url) composer = Composer(master) i=0 for object in reportsforPDF: if i>0: doc = Document(reporturl + object.document.url) composer.append(doc) i+=1 storage = settings.MEDIA_ROOT + '/merged/{}.docx'.format(filtervalue) composer.save(storage) pythoncom.CoInitialize() convert(settings.MEDIA_ROOT + '/merged/{}.docx'.format(filtervalue)) context = { 'pdf_url': '/media/merged/{}.pdf'.format(filtervalue) } return render(request, 'report/myfiles.html', context=context) Also how can I use get_query_set inside the post function because my current code returns no objects? -
Django Web Server is not opening open source project
I'm trying to run the Django medicine web-app. it's an open-source project. here's the link https://github.com/jai-singhal/croma when I run this command python manage.py runserver I got this error enter image description here -
Redirect from one admin view to another model view in Django
I'm trying to find a way of opening different admin view on column selection. My very simplified models are following: class modelA(models.Model): created = models.DateTimeField(auto_now_add=True) description = models.CharField(max_lenght=200) class modelB(models.Model): modelsA = models.ForeignKey(on_delete=models.CASCADE, related_name='modelBs') value = models.IntegerField() And in admin I have following view: class modelA_Admin(admin.ModelAdmin): list_view = ('__str__', 'total_modelBs') def total_modelBs(self, obj): try: total = obj.modelBs.all().count() except modelB.DoesNotExist: total = 0 return total What I'd like to get is be able to open modelB Admin view with values filtered for those that have given modelA id once I click on value total_modelBs. Any idea, how this can be achieved? -
Css and Javascript failing to load in html
Trying to add a slider to an html page in my django project, but css and javascript is not loading. Because of this instead of the slider being an actual slider ie. images sliding across, I get a vertical line of pictures. These are the errors i am getting in my browser console Failed to load resource: the server responded with a status of 404 (Not Found) slider.js:1 Uncaught ReferenceError: $ is not defined at slider.js:1 main.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) countdown.js:26 Uncaught TypeError: Cannot set property 'innerHTML' of null at updateClock (countdown.js:26) at initializeClock (countdown.js:36) at countdown.js:41 main.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) slider.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) This is the structure of my static folder static -->second ---->css >app slider.css ---->js >app slider.css my html {% load static %} <link rel="stylesheet" href="{% static 'second/css/app/slider.css' %}"> <script src="{% static 'second/js/app/slider.js' %}"></script> <div class="container"> <h3>Our Partners</h3> <section class="customer-logos slider"> <div class="slide"><img src="https://image.freepik.com/free-vector/luxury-letter-e-logo-design_1017-8903.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/3d-box-logo_1103-876.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/blue-tech-logo_1103-822.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/colors-curl-logo-template_23-2147536125.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/abstract-cross-logo_23-2147536124.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/football-logo-background_1195-244.jpg"></div> <div class="slide"><img src="https://image.freepik.com/free-vector/background-of-spots-halftone_1035-3847.jpg"></div> <div … -
How to assign custom color in google column chart based on value (Django)
I have values : m=72 n=34 z=59 I got the fowlloing google column chart : <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load("current", {packages:['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ["Apple", {{m}}, "green"], ["Orange", {{n}}, "red"], ["Grape", {{z}}, "orange"],); var view = new google.visualization.DataView(data); view.setColumns([0, 1, { calc: "stringify", sourceColumn: 1, type: "string", role: "annotation" }, 2]); var options = {title: "Fruits",width: 1000, height: 400, bar: {groupWidth: "95%"},}; var chart = new google.visualization.ColumnChart(document.getElementById ("columnchart_values"));chart.draw(view, options);} </script> <div id="columnchart_values" style="width: 900px; height: 300px;"></div> i want to color values m,n or z in the following way: if value (m,n or z) more than 70 color green if value (m,n or z) more than 50 but less than 70 color orange if value (m,n or z) less than 50 color red Any help is appreciated. -
Djnago, is it possible to create multiple status choice with a model?
This is my actually models.py, that give me the possibility to create the status for a multiple choice: class Status(models.Model): slug = models.SlugField(unique=True) category = models.TextField() class Example(models.Model): category= models.ForeignKey(Status) I want to have the possibility to add a sub category. In other words, if I create a new category "Product" in my status model, I want to have the possibility to create the sub category choice, dipendet from the category, and selectable in my Example model in a new field called sub_category. -
TemplateDoesNotExist at /login/ registration/login.html
While I am creating login and logout using built-in login() and logout() views the following error occured. The templates login.html, logout.html are present in 'djangobin/templates/djangobin/login.html', 'djangobin/templates/djangobin/logout.html' TemplateDoesNotExist at /login/ registration/login.html Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Reference website: Overiq.com Reference website Link: https://overiq.com/django-1-11/django-logging-users-in-and-out/#using-built-in-login-and-logout-views Python version: 3.8.2 Django version: 3.0.5 OS: Windows 8.1 (32-bit) In settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'djangobin', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.common.BrokenLinkEmailsMiddleware' ] ROOT_URLCONF = 'django_project.urls' In urls.py: from django.contrib.auth.views import LoginView, LogoutView url(r'^login/$', LoginView.as_view(), {'templates_name': 'djangobin/login.html'}, name='login'), url(r'^logout/$', LogoutView.as_view(), {'templates_name': 'djangobin/logout.html'}, name='logout'), In login.html: {% extends "djangobin/base.html" %} {% block title %} Login - {{ block.super }} {% endblock %} {% block main %} <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6"> <h4>Login</h4> <hr> {% if messages %} {% for message in messages %} <p class="alert alert-info">{{ message }}</p> {% endfor %} {% endif %} <form method="post"> {% csrf_token %} <table class="table"> {{ form.as_table }} <tr> <td>&nbsp;</td> <td><button type="submit" class="btn btn-primary">Submit</button></td> </tr> </table> </form> </div> <div class="col-lg-6 col-md-6 col-sm-6"> <h4>Related Links</h4> <p> <a href="/password-reset/">Forgot Password?</a> <br> <a href="/register/">Create new account.</a> <br> <a href="#">Feedback</a> </p> </div> </div> {% endblock %} -
Is there a left join in django.extra() which can help me to join tables without any relationship in django
class Ordman(models.Model): pcod = models.CharField(db_column="PCOD", max_length=6) class Meta: managed = False db_table = "ORDMAN" class Shademst(models.Model): code = models.CharField(db_column="CODE", primary_key=True, max_length=6) class Meta: managed = False db_table = "SHADEMST" These both are connected without any relationship and I need to fire a left join query with the help of extra() in ORM in django but the join I can apply is inner join so can anyone help me to figure out how to apply left join in it. The database is a legacy database so can't do changes on it -
Django: Import models.py in other views.py
Basically a user can login, once the user is logged in she/he can takes a quiz, after have taken the quiz, on user_profile.html page she/he can sees the score. If the score is > x then can see the progress bar and some jobs applications. I created all to the point of "if score > x shows the progress bar" I can't print the {{ job.posizione }} I created on the "jobs" app. The idea was to import the jobs/models.py on the core/views.py but then I get stuck on a nested for loop on the user_profile.html template core/views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.list import ListView # Create your views here. from quiz.models import Questions def homepage(request): return render(request, 'core/homepage.html') def userProfileView(request, username): user= get_object_or_404(User, username=username) categories = Questions.CAT_CHOICES scores = [] for category in categories: score = Questions.objects.filter(catagory=category[0], student= request.user).count() scores.append(score) context = { 'user' : user, 'categories_scores' : zip( categories,scores) } return render(request, 'core/user_profile.html' , context) class UserList(LoginRequiredMixin, ListView): model = User template_name = 'core/users.html' core/user_profile.html {% extends 'base.html'%} {% block content %} <br> <div class="card-header"> <h3> {% if request.user == user %} Il tuo {% endif %} Profilo … -
django: OperationalError: no such column: child.parent_ptr_id
I am currently working on a django project where I want to make a model that inherits from another model: from django.db import models import uuid . . . class Asset(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) act_life_cycle_stage = models.CharField(max_length=255, default="Undefined Yet") act_hierarchy_level = models.CharField(max_length=255, default='Undefined Yet') class Test(Asset): name = models.CharField(max_length=5) But when I am in the admin window and I want to make a new Test-entry I get following error: django.db.utils.OperationalError: no such column: injectionmolding_test.asset_ptr_id Which I don't understand since I did python manage.py makemigrations beforehand and I also have a normal looking migration file: from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ ('injectionmolding', '0005_auto_20200419_1821'), ] operations = [ migrations.CreateModel( name='Asset', fields=[ ('uuid', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('act_life_cycle_stage', models.CharField(default='Undefined Yet', max_length=255)), ('act_hierarchy_level', models.CharField(default='Undefined Yet', max_length=255)), ], ), migrations.CreateModel( name='Test', fields=[ ('asset_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='injectionmolding.Asset')), ('name', models.CharField(max_length=5)), ], bases=('injectionmolding.asset',), ), ] What am I doing wrong? -
Docker: Django + Mssql
Good morning everyone, I have a problem running Django + MSSQL on the docker outside the docker it runs normally, when I try to use it in the Docker the error occurs. ERROR DJANGO + MSSQL settings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'MyDB', 'USER': 'MyUser', 'PASSWORD': 'MyPass', 'HOST': 'MyHost', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } } My Docker File FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN mkdir /Python WORKDIR /Python ADD requirements.txt /Python/ RUN pip install -r requirements.txt ADD . /Python/ My docker-compose version: '3' services: projeto-ouvidoria: build: ../images/ command: python3 Django/projetoOuvidoria/manage.py runserver 0.0.0.0:8000 container_name: PythonDjango volumes: - ../../Django:/Python/Django ports: - "8000:8000" - "3306:3306" extra_hosts: - "desenvDocker:192.168.99.2" My requeriments.txt django>=2.2,<3 djangorestframework>=3.11.0,<3.12.0 django-jet2 django-mssql -
Is there a way to customize authentication views that are included in URLConf?
In Django 3.0 documentation, it is said that the easiest way to implement authentication views is to just "include the provided URLconf in django.contrib.auth.urls in your own URLconf". Is there a way to modify some attributes of these class-based views without explicitly referencing them? For example, if I want to modify the extra_context attribute of the LoginView, is it obligatory to handle it as documented: from django.contrib.auth import views as auth_views from datetime import datetime urlpatterns = [ path('accounts/login', auth_views.LoginView.as_view(extra_context={'title':'Log In', 'year':datetime.now().year})), ] or is there a shortcut for modifying this view in the included URLConf? -
Display record from database to template
Hi i am building a project where there is a form which login user submits , so the user can submit the form multiple times i have used ForeignKey . Now i am struggling to display all the records associated with the user . for example : user 'abc' has fill form and he comes again and fill form so i want to show both the form details of user abc in my template , I am missing something as new to django views.py def PostTest(request): if request.method == 'POST': test = UserTest() test.user = request.user test.name = request.POST['name'] test.email = request.POST['email'] test.location = request.POST['location'] test.time = request.POST['time'] test.save() return render(request, 'posts/test.html') test.html {{ user.usertest.location }} models.py class UserTest(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) email = models.EmailField() location = models.CharField(max_length=255) time = models.IntegerField() test_submitted = models.BooleanField() so i want to get the location filed in my template as user fill multiple times the form so i want all the location of that user in my django template , something looping may work but as newbie don't know how to use it. -
custom css switch does not run javascript function
I have a custom switch in CSS that I am using in a template for django. I am loading the javascript file properly but when I go to use the switch I don't get the expected result. The expected result is that the background would change colour this does not work using the switch. I added a button into the template to see if the button would work which it did, javascript file: function myFunction() { var element = document.body; element.classList.toggle("dark-mode"); } HTML switch this does nothing: <div class="onoffswitch" style="position: fixed;left: 90%;top: 4%;" onclick="darkMode()"> <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" onclick="darkMode"> <label class="onoffswitch-label" for="myonoffswitch"> <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span> </label> </div> HTML button that does do what is expected. <button onclick="darkMode()">Toggle dark mode</button> CCS if this is causing the problem: .onoffswitch { position: relative; width: 90px; -webkit-user-select:none; -moz-user-select:none; -ms-user-select: none; } .onoffswitch-checkbox { display: none; } .onoffswitch-label { display: block; overflow: hidden; cursor: pointer; border: 2px solid #000000; border-radius: 20px; } .onoffswitch-inner { display: block; width: 200%; margin-left: -100%; transition: margin 0.3s ease-in 0s; } .onoffswitch-inner:before, .onoffswitch-inner:after { display: block; float: left; width: 50%; height: 30px; padding: 0; line-height: 30px; font-size: 16px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold; box-sizing: border-box; … -
Update the value of a model dynamically, by performing operations
I have 2 models, Order and Expense. The Expenses are based on Order ID. Whenever I add an expense, this should add to the total expense of the respective order. Models.py class Order(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="order",blank=True,null=True) client_name = models.CharField(max_length=100) event_name = models.CharField(max_length=100) event_description = models.TextField(max_length=300,null=True,blank=True) expenses = models.PositiveIntegerField(default=0,null=True,blank=True) def __str__(self): return self.client_name class ProjectExpense(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="project_expense",null=True,blank=True) order_id = models.PositiveIntegerField(default='0',null=True,blank=True) exp = models.CharField(max_length=100) exp_desc = models.TextField(null=True,blank=True) amount = models.PositiveIntegerField(default='0') def __str__(self): return self.exp -
Django fail to use S3 for media storage
Good Day, I am trying to upload my media files to Amazon S3, I have created a bucket with public access, I have also created an IAM with full access of S3, and am using the keys. The site is developed, I wanted to try configuring S3 before moving it to server. I am able to upload files, but when I am trying to fetch files. I get the following error: The request signature we calculated does not match the signature you provided. Check your key and signing method. Here is my settings.py file: MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = "/media/" LOGIN_REDIRECT_URL = 'books:home' LOGIN_URL = "users:login" AWS_ACCESS_KEY_ID = "" AWS_SECRET_ACCESS_KEY = "" AWS_STORAGE_BUCKET_NAME = "" AWS_S3_FILE_OVERWRITE =False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" AWS_S3_SIGNATURE_VERSION = "s3v4" AWS_S3_REGION_NAME = "ap-south-1" Here is my pip freeze: asgiref==3.2.7 boto3==1.12.44 botocore==1.15.44 cachetools==4.1.0 certifi==2020.4.5.1 chardet==3.0.4 Django==3.0.5 django-bootstrap-form==3.4 django-crispy-forms==1.9.0 django-filter==2.2.0 django-filters==0.2.1 django-mailgun==0.9.1 django-storages==1.9.1 docutils==0.15.2 google-api-core==1.17.0 google-auth==1.14.1 google-cloud-core==1.3.0 google-cloud-storage==1.28.0 google-resumable-media==0.5.0 googleapis-common-protos==1.51.0 idna==2.9 jmespath==0.9.5 numpy==1.18.3 pandas==1.0.3 Pillow==7.1.1 protobuf==3.11.3 pyasn1==0.4.8 pyasn1-modules==0.2.8 python-dateutil==2.8.1 pytz==2019.3 requests==2.23.0 rsa==4.0 s3transfer==0.3.3 six==1.14.0 sqlparse==0.3.1 urllib3==1.25.9 xlrd==1.2.0 Attached is the screenshot of the error -
Inheritance from an AbstractUser based Model in django 2.7
I have a Custom User Model extending the AbstractUser and it works fine. But now i want to create another Model that is extending my Custom User Model like this in models.py: class CustomUser(AbstractUser): phone = models.CharField(max_length=10, null=False, unique=True) town = models.CharField(max_length=25, null=False) class DeleveryPerson(CustomUser): code = models.CharField(max_length=10, null=False, unique=True) The problem is that the table DeleveryPerson is created with just the field "code" when I expected it to also have fields coming from the CustomUser model. So how can i achieve that kind of inheretane between CustomUser and DeleveryPerson. Thk! -
Can i make retrieve request in django from model parameter?
I am using Django rest framework for my api. In my views.py file i am using Viewset.ModelViewset. class SchemaViewSet(viewsets.ModelViewSet): queryset = models.Schema.objects.all() serializer_class = serializers.SchemaSerializer My URL for this is : http://127.0.0.1:7000/api/schema/ THis is giving me GET and POST option. The response is something like this: { "id": 1, "name": "yatharth", "version": "1.1" }, To Delete/Put/Patch i have to pass id which is 1 like this: http://127.0.0.1:7000/api/schema/1/. Can i do this by name like this: http://127.0.0.1:7000/api/schema/yatharth/ instead of id. My model.py (I can Set name to unique = True) class Schema(models.Model): """Database model for Schema """ name= models.TextField() version = models.TextField() def __str__(self): return self.name -
I want to reformate drf viewset url that uses @action decorator
how to reformat URL from http://localhost:8000/articles/{id}/comments/ to http://localhost:8000/articles/comments/{id}/ class ArticlesViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet ): queryset = Articles.objects.order_by("-created") serializer_class = ArticlesSerializer @action(methods=["delete"], detail=True) def comments(self, request, *args, **kwargs): comment = Articles.objects.filter(comment=id).first() .......... how to make url as described above? -
Django "ljust" built-in template tags not working
I'm trying to use Django's ljust template tag but cannot get it to work. What am I doing wrong? <p class="card-text">{{article.excerpt|ljust:"400"}}</p> -
Django Model unittest
Good Morning!, I'm trying to write a tests for my app, but unfortunately something all the time is breaking up. Despite I create instance of the Post model, i'm still getting the same error. error ERROR: setUpClass (blog.tests.test_models.PostModelTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\madas\OneDrive\Pulpit\Code\git-projects\django_tutek\djangoenv\lib\site-packages\django\db\models\base.py", line 456, in __init__ rel_obj = kwargs.pop(field.name) KeyError: 'author' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\madas\OneDrive\Pulpit\Code\git-projects\django_tutek\djangoenv\lib\site-packages\django\db\models\base.py", line 461, in __init__ val = kwargs.pop(field.attname) KeyError: 'author_id' model def get_default_user(): return User.objects.get(is_superuser=True) class Post(models.Model): field = models.TextField(choices=TOPIC, default='N/A') title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True, null=False) author = models.ForeignKey(User, on_delete= models.CASCADE, default=get_default_user) content = RichTextUploadingField() img = ResizedImageField(size=[1600, 1200], upload_to='post_pics', default='default.jpg') created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', kwargs={'slug': self.slug}) tests from django.test import TestCase from blog.models import Post class PostModelTest(TestCase): @classmethod def setUpTestData(cls): Post.objects.create(field='Python', title='Pierwszy post', slug='pierwszy-post', status=1) def setUp(self): self.post = Post.objects.get(title='Pierwszy post') def test_author(self): self.assertEqual(self.post.author == 'adam') -
How to query the database in Django forms?
I have a model: class Registration(models.Model): student_name = models.CharField(max_length=50) season = models.OneToOneField(Season) subject = models.OneToOneField(Subject) address = models.TextField() class Meta: unique_together = (('student_name', 'selected_season', 'selected_subject'),) I want to create a form for this model where the user will be given the option to select the subject based on the season that they selected. I have models for them as well: class Subject(models.Model): subject_name = models.CharField(max_length=50) ... class Season(models.Model): season = models.CharField(max_length=2, primary_key=True) subject = models.ManyToManyField(Subject) ... I dont know how to query the Form. Should It be a ModelForm or a regular Form? How to query the database in the form? -
Chart js in Django not showing when sent variable from views.py
I will plot horizontal bar chart in html but it's not showing. I send 2 variable from views.py are {{top5StockCode}} (code of item) and {{top5TotalSales}} (sale amount). The values of {{top5StockCode}} that views.py sent is ['23166', '21108', '85123A', '48185', '22470'] and {{top5TotalSales}} is [2671740, 227322, 171770, 158120, 143808]. This is my code in html <div class="top5"> <p class="topicTop5">Top 5 Selling Products</p> <canvas id="top5"></canvas> </div> <script> var top5 = document.getElementById('top5').getContext('2d'); var chart = new Chart(top5, { type: 'horizontalBar', data: { labels: {{top5StockCode}}, datasets: [{ label: 'Top 5 selling products ', backgroundColor: '#CE3B21', borderColor: 'rgb(255, 99, 132)', data: {{top5TotalSales}} }] }, options: { legend: { display: false }, responsive: true, maintainAspectRatio: false, scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); </script>