Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use output of multiple views in one view with single url
So i am fairly new to Django and here is what i want: Say i have Three Views, View 1, 2 and 3. Each one with their own Template, Http response ,context and everything. Now i know how to Use 3 separate URLs for each view but what i would like to do is Just have one url for say View 3 and Outputs of View 2 and 3 are merged or concatenated whatever you wanna say in the view 3 itself. I am doing this because i have a lot of context and doing one view and single template results in a large code. At the moment i am using Class Views but i am open to you use function views. I want to know if there is a way i can Get Output/Results of View 1 and 2 in View 3 combined. Note: If someone is familiar with React and the components thats kind of what i am trying to do. Like making two components separately and then have a container component to call them. P.S. i am not using react i just thought this will explain what i am trying to do. -
Using react, axios and django, i'm trying to send data from my client side to my server but I can't get the data
I'm trying to recive POST data from my client side and i'm getting the following error: TypeError: registrar_usuario() missing 1 required positional argument: 'usuario' Here is my code from the client side: const onSubmit = e =>{ e.preventDefault(); alert("Enviando..."); const nuevoUsuario = { nombre: datosUsuario.nombre, apellido: datosUsuario.apellido, correo: datosUsuario.email, contrasenia: datosUsuario.password } //const resultado = ApiUtils.registrarUsuario(nuevoUsuario); const resultado = axios.post('http://localhost:8000/api/registrar_usuario/', nuevoUsuario); console.log(resultado); } and here the server side: @api_view(['POST']) def registrar_usuario(request, usuario): print(usuario) return Response(status=status.HTTP_200_OK) i need help, it's my first time using react, axios, and django so any advise would be helpful -
Django CyclicDependencyError in model
I'm trying to perform a makemigrations, but it errors out like this: django.utils.topological_sort.CyclicDependencyError: Cyclic dependency in graph: (<CreateModel name='CasprAdminStatusDef', fields=[('assessment_type', <django.db.models.fields.related.OneToOneField>), ('status_name', <django.db.models.fields.CharField>)], options={'db_table': 'CAsPr_Admin_Status_Def', 'managed': False}, bases=(<class 'django.db.models.base.Model'>,), managers=[]>, {<CreateModel name='CasprAdminStatusDef', fields=[('assessment_type', <django.db.models.fields.related.OneToOneField>), ('status_name', <django.db.models.fields.CharField>)], options={'db_table': 'CAsPr_Admin_Status_Def', 'managed': False}, bases=(<class 'django.db.models.base.Model'>,), managers=[]>}) The model that is erroring out is very simple. I don't see the problem: class CasprAdminStatusDef(models.Model): assessment_type = models.OneToOneField('self', models.DO_NOTHING, db_column='Assessment_Type', primary_key=True, related_name='+') # Field name made lowercase. statusid = models.ForeignKey('self', models.DO_NOTHING, db_column='StatusID') # Field name made lowercase. status_name = models.CharField(db_column='Status_Name', max_length=50, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'CAsPr_Admin_Status_Def' unique_together = (('assessment_type', 'statusid'),) This model was created by inspectdb. What's going on here? -
POST REQUEST Dynamic Form
I'm trying to make a POST REQUEST to Django-Default DB with a dynamic form that when the users need it, it can add another text-field, so the idea behind this is that the user can add those two register to the DB. Although, the actual situation is when the user submit the info through the form, it only returns one row of data, instead of returning two rows of data. What I'm doing wrong? views.py def recursos(request): if request.method == 'POST': materiaprima = request.POST.getlist('MateriaPrima') tiempo = request.POST.getlist('Tiempo') valorunitario = request.POST.getlist('ValorUnitario') mat_list = [] for mp,t,va in zip(materiaprima, tiempo, valorunitario): mat = Recursos(MateriaPrima=mp, Tiempo=t, ValorUnitario=va) mat_list.append(mat) Recursos.objects.bulk_create(mat_list) return render (request, "Portafolio/materiaprima.html") materiaprima.html {% extends "Portafolio/layout.html" %} {% load static %} {% block scripts %} <script src = "{% static 'Portafolio/scriptmateriaprima.js' %}" type="text/javascript"></script> {% endblock %} {% block content %} <form action = "{% url 'recursos' %}" method="POST" class="form mt-5" id="infra"> {% csrf_token %} <h1>Factibilidad Técnica y Operativa</h1> <h2>Disponibilidad de Materia Prima</h2> <main class="container"> <section class="row"> <div class="col-lg-4 mb-2"> <input name='MateriaPrima' class="form-control" type="text" placeholder="Materia Prima"> </div> <div class="col-lg-4 mb-2"> <input name='Tiempo' class="form-control" type="text" placeholder="Cantidad"> </div> <div class="col-lg-4 mb-2"> <input name='ValorUnitario' class="form-control" type="text" placeholder="Valor Unitario"> </div> </section> </main> <nav class="btn-group"> <button id='add' class='btn … -
Why my -webkit-background-clip: text ; is not working
I m tring to make an animation for text with gradient but my -webkit-background-clip:text; is not working please check whats the issue here: h2{ display: flex; justify-content: center; align-items: center; position: absolute; left: 10%; top: 10%; font-size: 150%; font-weight: 800; color: white; width: 10%; height: 20%; -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent; background-size: 400%; background: linear-gradient( to right bottom, rgba(255,255,255,.9), rgba(255,30,80,1) 130%); animation: animate 10s linear infinite; } <div id="myname"> <h2>Priyanshu Kumar</h2> </div> -
Django: How can I create a model from a POST request?
To put it on context, I would like to let users create models using a form in the templates. That way the can create multiple different models if necessary. Example: Let's say, as an user I want to create a form that takes the name and phone number of a person. Then I'd like to create another form that takes a name, a time and a phone number. What would be the best approach to doing this task? -
Update data in postgres using def update - Django
I have a method to create a new item in my database that works fine. But when creating the similar method to update, it is creating a new item instead of updating the existing one, and if I force the id to pass in "data", it complains that this id already exists... My CODE: class EventsAttachmentsViewSet( mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): permission_classes = [permissions.AllowAny] queryset = EventAttachment.objects.all() serializer_class = EventAttachmentSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def update(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data self.perform_update(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) -
Django Auth Group refuses to change in UpdateViews
I'm having a problem to update the User Group field after the User creation. The focus here is do this kind of thing outside the Admin page, in common UpdateView that will have limited access for certain groups. What bugged me is that the Group selection and saving of the EditForm and EditView is identical to the CreationForm/CreationView, and those work flawlessly. It just refuses to change, it doesn't throw any error, just like there were no relations between this tables (auth_group and users_customuser_groups) at all. views.py class UserEdit(LoginRequiredMixin, UpdateView): form_class = EditUserForm template_name = 'registration/edit_profile.html' success_url = reverse_lazy('dashboard') def get_object(self): return self.request.user def post(self, request, *args, **kwargs): form = EditUserForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() group = Group.objects.get(name=form.cleaned_data['group']) group.user_set.add(user) group.save() form.save() return redirect('dashboard') models.py from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, Group from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager from institutes.models import Institute class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) name = models.CharField(max_length=255) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() group = models.ForeignKey(Group, on_delete=models.CASCADE, default=1) institute = models.ForeignKey(Institute, verbose_name='institute', on_delete=models.CASCADE) def __str__(self): return str(self.name) forms.py class EditUserForm(UserChangeForm): … -
Django/CSS: I'm trying to make a sidebar but when I run the website its a header, what did I do wrong?
Creating a sidebar with "Home", "Create", and "View" When running server the "sidebar" is on top, running left to right <html> <head> sidebar: .sidenav { height:100% width:160px position:fixed; z-index: 1; top: 0; left: 0; background-color: #111; overflow-x: :hidden; padding-top:20px; } .sidenav a { padding:6px 8px 6px 16px; text-decoration: none; font-size: 25px; color: #818181; display:block; } For when the buttons are hovered over .sidenav a:hover{ color: #f1f1f1; { -
Erro no Django: TypeError: expected string or bytes-like object na criação de tabelas no models
Boa noite! Estou criando um banco de dados pelo Django, mas ao executar o comando python manage.py migrate, recebo essa mensagem de erro: > python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, core, sessions Running migrations: Applying core.0002_auto_20210621_2027...Traceback (most recent call last): File "C:\Users\mat_a\Documents\GitHub\ProjetoSalvePets\Projeto\SalvePets\manage.py", line 22, in <module> main() File "C:\Users\mat_a\Documents\GitHub\ProjetoSalvePets\Projeto\SalvePets\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\migrations\migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 330, in add_field self._remake_table(model, create_field=field) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 191, in _remake_table self.effective_default(create_field) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\backends\base\schema.py", line 310, in effective_default return field.get_db_prep_save(self._effective_default(field), self.connection) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\models\fields\__init__.py", line 842, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "C:\Users\mat_a\Desktop\env\env\lib\site-packages\django\db\models\fields\__init__.py", line … -
How do I get collectstatic to work when running a Django/React App on Heroku?
I have a Django/Wagtail/React App that works in my dev server, but when I try to build it on Heroku, I get a ***FileNotFoundError when it runs collectstatic. I'm using Whitenoise to serve the static files and have Gunicorn installed with its corresponding Procfile. This is the error log I get on Heroku: -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in Pipfile.lock -----> No change in requirements detected, installing from cache -----> Using cached install of python-3.9.5 -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 -----> Installing dependencies with Pipenv 2020.11.15 Installing dependencies from Pipfile.lock (d71a71)... -----> Installing SQLite3 -----> $ python manage.py collectstatic --noinput BASE_DIR /tmp/build_73214ee4 BASE_DIR + FRONTENTD: /tmp/build_73214ee4/frontend/build/static Traceback (most recent call last): File "/tmp/build_73214ee4/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/finders.py", line 130, in list for path in utils.get_files(storage, ignore_patterns): File … -
Does formset_factory inherit the clean/validation methods of the form it extends?
Basically the title. I want to know if for example: forms.py class TestForm(forms.Form): field1... def clean_field1(self): field1... views.py formset = formset_factory(TestForm)... formset.is_valid() <---? Will formset.is_valid() call clean_field1()? -
How to retrofit an auto increment id field back to a model in Django
I have the following model: class Team(models.Model): slug = models.SlugField(primary_key=True) name = models.CharField(max_length=50) However I realised this is a dumb design since I cannot rename the slug in admin, so I want to add the auto increment id back to the model, by removing the primary_key=True from slug field, however, makemigrations requires me to put in the default value for the id field, how do I go about doing it? class Team(models.Model): slug = models.SlugField(unique=True) name = models.CharField(max_length=50) -
webpack no output file is created
I try to use webpack to overwrite sass. when i run npx webpack --config config.js I get "./src/js/index.js... compiled successfully in 75 ms however, no files are created in my djano project static/js and static/scss If I create the files, they remain empty as no data is pass to them. I note this information is passed to dist/main.js but not to my django project. How can i export the index.js/index.scss files from webpack to my django project? my config.js is: const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module.exports = { entry: './src/js/index.js', mode: 'development', output: { filename: 'index.js', path: "/carmuse8/static/js/", }, module: { rules: [ { test: /\.(scss)$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader' ] }, ], }, plugins: [ new MiniCssExtractPlugin({ filename: '../css/index.css', }), ] }; Thanks for any input that will allow me to advance. -
Django admin panel search bar not work (Related Field got invalid lookup: icontains)
I have in models class Wallet(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) sats_balance = models.PositiveBigIntegerField(default=0, validators=[MinValueValidator(0)]) pin = models.CharField(max_length=15, default=pin_generator) pin_saved = models.BooleanField(default=False) and in the wallet app admin.py from django.contrib import admin class WalletAdmin(admin.ModelAdmin): search_fields = ['user'] the search bar has exist but when I search for any user I got this error raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: icontains -
Structure of an HTML post Request vs Django HTML Post Request
I have the following HTML form code which I am trying to translate to Django Templating Language. <form action="https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST"><input type=hidden name="oid" value="00D280000016jv0"> <input type=hidden name="retURL" value="https://url/form/"> <label for="first_name">First Name</label><input id="first_name" maxlength="40" name="first_name" size="20" type="text" /><br> <label for="last_name">Last Name</label><input id="last_name" maxlength="80" name="last_name" size="20" type="text" /><br> <label for="email">Email</label><input id="email" maxlength="80" name="email" size="20" type="text" /><br> <label for="phone">Phone</label><input id="phone" maxlength="40" name="phone" size="20" type="text" /><br> </select><br><input type="submit" name="submit"> </form> I've looked at Django Templating Tutorials which tells me to create a view however I don't think that's necessary. What is the Django equivalent of this code? -
To reload or not reload - Is it better to send data to the server via ajax and then reload the page to see the result or update the DOM using js?
I have a fairly complex Django (3.1) site. On a couple of pages, I have some html/javascript code for the user to add/edit/delete comments. The script packages the comment and other bits and sends it to the server in an ajax POST request so the comment can be added/updated/deleted to/from the database. The script then gets an acknowledgement from the server, and, currently, it reloads the page so the new/edited/deleted comment can be seen at the bottom of the page. It all works fine in Chrome and Firefox. My questions is: Is it better practice to have the script add/edit/delete the comment html directly in the DOM based on the ajax response, rather than just reloading the page with the updated data? Why or why not? Thanks! Mark -
Django SQLite regex query is slow. Local SQLite regex query is fast. Why?
I have a small SQLite3 app that's basically a database search. When I do from main.models import Customer queryset = Customer.objects names = queryset.filter(name__regex = "[^aeiou]ica$") list(names) in ./manage.py shell, Django takes up to 5 seconds to return this result. Meanwhile on my local machine, if I do the same query in the sqlite shell, sqlite> select * from main_customer where name regexp "[^aeiou]ica$"; I get the result in less than a second. Where does the difference come from? Can Django be made to match the speed of my local query? -
is there a way to compute a field based on the value ot other two field in the same form, using ModelAdmin?
I want to compute based on two fields a third field using django and ModelAdmin. example when a write on the firsfield ["this is the value1"] and SecondField["this is the value2"] and then autocomplete a thirdField as [firstfield + SecondField] and then after all that save this info in a model with firstField,SecondField and ThirdField. -
Creating dropdown menu in django for user created data only in a different class
I'm new to programming and my first language/stack is Python and Django. I have figured out how to create a dropdown menu in my Script form that is pointing to a different class "Patient" but I can't figure out how to only show me data that the current user created. I'm confused if I should set this in my models.py, forms.py or in the views.py? Here is what I have that I think should be working but it is not. (Tried setting in the views.py) Models.py class Patient(models.Model): author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) patient_name = models.CharField(max_length=40, unique=True) def __str__(self): return self.patient_name class Script(models.Model): author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) patient = models.ForeignKey(Patient, on_delete=models.CASCADE, verbose_name='Primary Patient') So my patient field is my dropdown and it is looking at the Patient class grabbing the patient name string. Views.py class ScriptCreateView(LoginRequiredMixin, CreateView): model = Script template_name = 'script_new.html' success_url = reverse_lazy('script_list') fields = ( 'patient', 'drug_name', 'drug_instructions', 'drug_start_day', 'drug_start_time', 'drug_hours_inbetween', 'drug_num_days_take', ) #This sets user created fields only?? def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter( author=self.request.user ) #This sets the author ID in the form def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form ) Forms.py class ScriptForm(forms.ModelForm): class Meta: model = Script fields = '__all__' #This … -
Deploy django to GAE standard from cloud build
I run following bash commands from my local machine to deploy django project to App engine. python manage.py migrate python manage.py collectstatic --noinput gsutil rsync -R static/ gs://xyz4/static gcloud config set project project_name_1 gcloud app deploy --quiet I would like to set it up on cloud build. I have enabled PUSH triggers on cloud build. Need help in creating cloudbuild.yaml file -
Django template {%url %} formatting
When I use {% url %} method to create link {% url app_name:sub_directory:url.linkfield %} it is producing error in the console i.e. raise TemplateSyntaxError("Could not parse the remainder: '%s' " django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: ':staff:url.linkfield' from 'app_name:staff:url.linkfield' This is my url.py app_name="application_name" urlpatterns=[ url(r"^staff/",include('application_name.staff_url', namespace='staff')), url(r"^customer/",include('application_name.customer_url', namespace='customer')), ] my staff_url.py from application_name import views app_name="staff" urlpatterns=[ url(r"^customers/",views.customers, name='customers'), url(r"^orders/$", views.orders, name='orders'), url(r"^payments/$", views.payments, name='payments'), ] my customer_url.py from application_name import views app_name="customer" urlpatterns=[ url(r"^items/",views.items, name='items'), url(r"^checkout/$", views.checkout, name='checkout'), url(r"^make_payment/$", views.make_payment, name='make_payment'), ] staf url would be staff/orders or staff/payments customer urls would be customer/items or customer/checkout etc Please what can i do -
Trouble mapping Django URLs
I've completed all of the sections of the Django tutorial and have started my own project now to practice. I am back at the beginning tutorial where it talks about views/mapping urls. I also am following this tutorial for trying to display a table For whatever reason, I cannot figure out why when I try to hit http://127.0.0.1:8000/show/, it returns 404. I've been staring at this for the last hour and have been going back and forth between the tutorial and my code. I had to do things a little bit differently than the 2nd mentioned tutorial, mainly that they didn't talk about creating an app level urls.py file. Everything up to this point has worked fine. The models.py file created the table within the mysql database, as I can see it in workbench. My project structure is like this: mywebsite (project) displaydata (app) Here is my project level urls.py file located in the mywebsite folder: from django.contrib import admin from django.urls import include,path urlpatterns = [ path('admin/', admin.site.urls), path('displaydata/', include('displaydata.urls')) ] Here is my app level urls.py file located in the displaydata folder: from django.urls import path from . import views app_name = 'displaydata' urlpatterns = [ path('', views.show, … -
Django Python current logged User
In my queryset I need to check status of post and if User mentioned in that post is the same as logged User. How can I get current logged User? queryset = Post.objects.filter(Q(status='Done') & (Q(person_1_username=current_logged_user) | Q(person_2_username=current_logged_user))) I know I should use something like code below, but I don't know how to get that value to 'current_logged_user' def my_view(request): username = None if request.user.is_authenticated(): username = request.user.username -
heroku can't migrat database: cannot cast type time without time zone to timestamp with time zone
I've got a Django app (running on Heroku ) with a simple form that contains a DateTimeField() the app work well locally, but after I push it to the heroku, and do heroku run python3 migrate, it will return an error : psycopg2.errors.CannotCoerce: cannot cast type time without time zone to timestamp with time zone LINE 1: ..." TYPE timestamp with time zone USING "date_added"::timestam... here is my models: from django.db import models from django.db.models.deletion import CASCADE from django.db.models.fields.related import ForeignKey from django.contrib.auth.models import User # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class BlogContent(models.Model): blogpost = ForeignKey(BlogPost, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField( auto_now_add=True) class Meta: verbose_name_plural = "blogcontents" def __str__(self): if len(self.text) > 50: return self.text[:50] + '...' else: return self.text from django.db import models from django.db.models.deletion import CASCADE from django.db.models.fields.related import ForeignKey from django.contrib.auth.models import User # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class BlogContent(models.Model): blogpost = ForeignKey(BlogPost, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField( auto_now_add=True) class Meta: verbose_name_plural = "blogcontents" def __str__(self): if len(self.text) > 50: return self.text[:50] …