Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django Meta class Fieldas and relation with database
i m begineer in django language and having difficulty in understanding django Meta class which is written inside another class hope someone could help me understanding it clear class UserRegistrationForm(UserCreationForm): email=forms.EmailField() class Meta: model=User fields=['username','email','password1','password2'] what are Meta fields and how is Meta class related to database ?? why this Meta class is used here? please help i m getting stuck for long time.. -
Trying to send an array to django database but get an error say Method not allow
I'm new to Django. I'm working on a app were the user type in an the name of the activities and the times.It than display it as a graph. When the user save it, the data will end up being in a json format through serialization. My problem right now is that it only save the last value of the user input and not all the input. Im trying to store an array into Django database. Found multiple answer but none help. I figure to maybe make a httprequest to send the value but any alternative will due. view.py from django.shortcuts import render from django.core import serializers from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_protect from page.templates.forms import ActivitiesForm from page.models import Activities from .serializers import ActivitiesSerializer from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from rest_framework.decorators import parser_classes from rest_framework.response import Response @api_view() def page_list(request): if request.method == 'GET': activities = Activities.objects.all() serializer = ActivitiesSerializer(activities, many=True) return Response(serializer.data) elif request.method == 'POST': # data = JSONParser().parse(request) serializer = ActivitiesSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=400) @csrf_protect def page_detail(request, pk): try: activities = Activities.objects.get(pk=pk) except Activities.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = ActivitiesSerializer(activities) return … -
Is perfoming calculations part of the backend?
Good night, I'm making a system using Django on the back end. I came up with a theoretical question, I am performing some calculations between existing inputs using JavaScript, and the values of those inputs I save in the database with Django. My question is, are these calculations I make between inputs part of the Backend? Or just the moment I use Django to save them? Thanks if you can help me! -
How can I list specific elements of all objects in Django model?
I know how to get post information from my model and display it like so: view: def post_view(request, pk): post = get_object_or_404(Listing, pk=pk) return render(request, 'post_view.html', {'post': post}) html: {% extends 'base.html' %} {% block content %} <div class="post"> {% if user.is_authenticated %} <a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a> {% endif %} <h2>{{ post.title }}</h2> <p>{{ post.street_address|linebreaksbr }}</p> <p>{{ post.city|linebreaksbr }}, {{ post.state|linebreaksbr }}</p> <p>{{ post.price|linebreaksbr }}</p> <p>{{ post.description|linebreaksbr }}</p> </div> {% endblock %} Now I need to make a new page called "listings." I've created a url and view already for this. I need my listings page to output post.thumbnail, post.title, and post.price for every object in my database with the is_live boolean set to True. Here is my current code: view: def listings(request): return render(request, 'listings.html') html: {% extends 'base.html' %} {% block title %}Listings{% endblock %} {% block content %} This is the listings page. {% endblock %} model: from django.db import models class Listing(models.Model): thumbnail = models.ImageField() title = models.CharField(max_length=255) description = models.TextField() street_address = models.CharField(max_length=255) city = models.CharField(max_length=255) state = models.CharField(max_length=255) price = models.FloatField() image1 = models.ImageField() image2 = models.ImageField() image3 = models.ImageField() is_live = models.BooleanField(default=False) class Meta: db_table = "listings" … -
Django - manage.py collectstatic saving to the wrong folder
When I run python manage.py collectstatic it saves to a folder called staticfiles I must have done something to make this happen, but I've searched for staticfiles and found no reference to it except 'django.contrib.staticfiles'. Here is my settings.py: INSTALLED_APPS = [ #some apps 'django.contrib.staticfiles', #some more apps 'tz_detect', ] # some more code STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(VENV_PATH, 'media_root') Expected outcome was for when python manage.py collectstatic is run, that an assets folder would be created, but this never happens. The staticfiles folder in addition to files from static folder also contains a tz_detect folder (from static assets from 3rd party package), an admin folder, and a staticfiles.json -
Django reverse for uid and token for activation email
I'm trying to send a custom email to activate a user's account. However, I cannot figure out how to do it. This method works with a regular URL link, but I can't seem to get the reverse right with the token and uid. from_email = '<info@domain>' #this is the custom template htmly = get_template('activation.html') #this is just the template of the message message = render_to_string('activation_email.html', { 'user':user, 'token': account_activation_token.make_token(user), 'uid':urlsafe_base64_encode(force_bytes(user.pk)), }) d = { 'username': username, 'url': reverse('activate', kwargs={'token':force_text(urlsafe_base64_encode(force_bytes(user.pk))), 'uid':urlsafe_base64_encode(force_bytes(user.pk))}))} subject = 'Email activation' html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, message, from_email, [request.user.email]) msg.attach_alternative(html_content, "text/html") msg.send() The error that I get is: django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments If I try to send it as one template, i.e. both the message and my custom html in the message. My html renders as a string. This is the email that I'm trying to send. The activation_email has the message below and activation.html has the custom email html template. activation_email.html {% autoescape off %} Hi {{ user.username }}, Email confirmation: http://domain{% url 'activate' uidb64=uid token=token %} {% endautoescape %} -
How do I add a reverse field value into the django serializer data set Part 2
I previously asked a similar question: How do I add a reverse field value into the django serializer data set But oddly, what worked for the first model doesn't work for the second. Here are my models: class ae(models.Model): opp_own = models.CharField(max_length = 50) class statement_line(models.Model): ae = models.ForeignKey(ae, on_delete=models.PROTECT) pay_date = models.DateField(null=True) approve_date = models.DateField() opp_name = models.CharField(max_length = 50) type = models.CharField(max_length = 10) document_number = models.CharField(null=True,max_length = 50,) ct_id = models.CharField(max_length = 50,validators=[ RegexValidator(regex='^CT', message='this didn\'t come from salesforce' )]) amt = models.FloatField() cur = models.CharField(default='USD',max_length = 3) class draws(models.Model): ae = models.ForeignKey(ae, on_delete=models.PROTECT) draw_type = models.CharField(choices=[('incentive pay','incentive pay'),('recoverable draw','recoverable draw')], max_length = 50) amt = models.FloatField() usd_amt = models.FloatField() cur = models.CharField(choices=[('USD','USD'),('EUR','EUR'),('AUD','AUD'),('IND','IND'),('GBP','GBP')],default='USD', max_length = 3) owe_date = models.DateField() sl = models.ForeignKey(statement_line, on_delete=models.PROTECT, null = True) This works fine: class drawsSerializer2(serializers.ModelSerializer): opp_own = serializers.SerializerMethodField() class Meta: model = draws fields = ['id','ae_id', 'ae','owe_date','draw_type','usd_amt','amt', 'opp_own'] extra_kwargs = { 'ae': {'write_only': True} } def get_opp_own(self, obj): return obj.ae.opp_own goods = draws.objects.filter(sl_id__isnull=True).order_by('-owe_date') serializer = drawsSerializer2(goods,many=True) serializer.data But inexplicably, this doesn't: class statement_lineSerializer2(serializers.ModelSerializer): opp_own = serializers.SerializerMethodField() class Meta: model = statement_line fields = ['id','ae_id','ae','pay_date','opp_name','type','document_number','ct_id','amt','cur','opp_own'] extra_kwargs = { 'ae': {'write_only': True} } def get_opp_own(self, obj): return obj.ae.opp_own goods2 = statement_line.objects.filter(pay_date__isnull=True).order_by('-approve_date') sl = … -
Why is my dlete button not deleting my database object? Django
I cobbled together a delete button and edited my view, it isn't working. Can someone help me fix it? I've moved some code around and tried some things but I can't get it to work. I need someone to show me what I'm doing wrong. My view: def post_edit(request, pk): post = get_object_or_404(Listing, pk=pk) if request.method == "POST": form = ListingForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('post_view', pk=post.pk) else: form = ListingForm(instance=post) if request.POST.get('delete'): post.delete() return redirect('listings') return render(request, 'post_edit.html', {'form': form}) My html: {% extends 'base.html' %} {% block title %}Post Edit{% endblock %} {% block content %} Hi {{ user.username }}! <p><a href="{% url 'logout' %}">logout</a></p> <h1>Edit listing:</h1> <p>The listing will only be viewable to users if "Is Live" is checked.</p> <form method="POST" enctype="multipart/form-data" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> <p>Click the button below to delete this listing. No second warning is given, once you click delete it will be removed.</p> <button type="delete" class="delete btn btn-default">delete</button> </form> {% endblock %} -
What is the correct way of using ManyToOne relation in Django
I am working on a Job Portal website and having some questions I wonder what's the correct way of using the relations in my case. For example: I have a CompanyProfile where a company can have multiple locations. I have a Job that can have multiple locations aswell. I have a Student, and a Student can make a Curriculum Vitae that exists of SkillSet, Education and Experience. This is wat I have now: A class CompanyProfile A Location Class where a CompanyProfile is a foreignkey of. A Job class where CompanyProfile and Location is foreinkey of. A Skillset, Education and Experience class all 3 of them have foreign key to CV. CompanyProfile class CompanyProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='company_profile') company_name = models.CharField(max_length=30) Location class Location(models.Model): company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE) address = models.CharField(max_length=100, null=True) zip_code = models.CharField(max_length=10, null=True) city = models.CharField(max_length=30, null=True) CV class Cv(models.Model): user = models.ForeignKey(StudentProfile, on_delete=models.CASCADE) Education, Experience and Skillset all same class Education(models.Model): cv = models.ForeignKey(Cv, on_delete=models.CASCADE) ... ... more fields. My question is. Is this the right way or should I Put a foreignkey in CompanyProfile class to Location. And should I put in CV 3 foreign keys of education, experience and skillset or is … -
i need cookie to get updated when user gets online again for notification
here is want i want to do: users can have collections of image about a certain thing (flowers for example). my websites looks at this collections and recommends related images. i want to give users a notification that a recommendation is ready even if browser is closed, users only need to be online. exactly like Pinterest. so i guess my cookie needs to see whether i'm online or not by trying to send something and if i am online my server will send the link to the recommendation section. three question: 1) what code should be in the cookie? 2) best way to send notification? 3) how to do the "sending links to users" asynchronously or with threading? i'm using django but it shouldn't matter, what would you do if you aren't using django, you don't have to answer all of that, if you know even one of them, it's still appreciated -
How do i run a shell script inside docker-compose
I have a use case in which i am trying to build a django based rest api and then use continuous integration using travis CI when changes are pushed to github. I am also using docker to build and docker-compose to scale my services. The problem is i want to run pytest and flake8 when i push my changes to github. Now i have not added any tests and hence the pytest command is giving an exit status of 5. To get around this i tried creating a script to do this : #!/bin/bash pytest; err=$? ; if (( $err != 5 )) ; then exit $err; fi flake8 ; But i cannot get docker-compose to run this . When i run the script using the command : docker-compose run app sh -c "run_script.sh" It gives the below error message : sh: run_script.sh: not found Below is my docker-compose yml file: version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" And below is the dockerfile: FROM python:3.7-alpine MAINTAINER Subhayan Bhattacharya ENV PYTHONUNBUFFERED 1 COPY Pipfile* /tmp/ RUN cd /tmp && pip install pipenv && pipenv lock --requirements > … -
Django-webpack-loader uses wrong port (npm run serve increases)
I'm new in webpack and vuejs. I have a problem with https://github.com/owais/django-webpack-loader As far as I know I need to start npm server to serve bundles. (feedbot) milano@milano-desktop:~/PycharmProjects/feedbot/frontend$ npm run serve > frontend@0.1.0 serve /home/milano/PycharmProjects/feedbot/frontend > vue-cli-service serve INFO Starting development server... 98% after emitting CopyPlugin DONE Compiled successfully in 1125ms App running at: - Local: http://localhost:8091/ <<<<<< HERE YOU CAN SEE THE PORT - Network: http://0.0.0.0:8080/ 10:37:55 PM I use this in my template: <div id="app"> <app></app> </div> {% render_bundle 'index' %} I can see in inspect that render_bundle renders wrong url: http://127.0.0.1:8080/index.js How do I make it work? The npm increases port instead of reusing 8080. So either I make django-webpack-loader to somehow recognize which port is in use or npm to reuse 8080. -
Django REST saves Image but returns wrong path
I am trying to save Community image and it saves it to /api/media/imagename.jpg, but when I retrieve a community it gives me /media/imagename.jpg without /api and then it can't find a image. So I have this Community model with FileField: class Community(models.Model): """DB Model for Community""" name = models.CharField(max_length=150, unique=True) description = models.TextField(default="") created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) number_of_members = models.IntegerField(default=1) community_image = models.FileField(blank=False, null=False, default="", upload_to="") def __str__(self): return self.name And I have this in my settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") And then this is in my urls.py: # urls.py in authentication_api application router = DefaultRouter() router.register('communities', views.CommunityViewSet) urlpatterns = [ path('', include(router.urls)), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # urls.py in root urls file urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('authentication_api.urls')) ] What should I change to it returns correct path to image. If you need any more code sample please comment. -
Python's scipy.optimize.fsolve crashes on (Webfaction) server despite working fine on similar localhost
I have a personal website, written in Django, hosted on Webfaction. I am trying to make a web tool in which users enter some numbers, the server receives them on the backend via AJAX, the server takes them as parameter inputs for a certain system of equations and solves it numerically using some Python package, and the server returns the solution via AJAX and Javascript presents it to the user. This process works flawlessly when I test it on Localhost. But on the Webfaction server, it often crashes after a few iterations of the numerical approximation function, as long as the inputs are not very simple. Both scipy.optimize.fsolve and scipy.optimize.root produce the issue. I have tried multiple "method"s, and they have all produced the issue. Also, I was originally on Webfaction's $10/mo "1GB RAM, 100GB SSD storage, 1TB bandwidth, shared server" plan, and I tried switching to their $30/mo "4GB RAM, 45GB SSD storage, 2TB bandwidth, 2 CPU cores, cloud server" plan--a setup similar to my Localhost--but this doesn't seem to have made even the slightest difference. from scipy.optimize import fsolve import logging from forms import * logger = logging.getLogger(__name__) def dppsubmit(request): form = ParamsForm(request.POST) if form.is_valid(): raw_pd = form.cleaned_data['params'] … -
Best way to send an email with the content of a model instance that may or may not rely on the content of a ManyToManyField
In my app, I need to email an invoice when a new model instance is created. The model, however, has a ManyToManyField that alters the content of the invoice if any of the ManyToManyField options are selected. If an instance is created without any of the ManyToManyField options selected, everything can be handled within the overridden save() method. If an instance is created with any of the ManyToManyField options selected, everything can be handled with the m2m_changed signal. The problem I have to be able to generate and send the invoice if the m2m_changed signal is fired, but if I do that, I don't want to send anything out in the save() method. But I also have to be able to generate and send the invoice in the save() method because if none of the ManyToManyField options are selected, the save() method is the only method that will fire. The question Is there a way to make sure the m2m_changed signal is always fired? Or, is there a way for the save() method to be aware that the m2m_changed signal will fire? -
How to update a django model's field from another model
So I have two models like this : class Subscription(models.Model): ... number_editions = models.IntegerField() ... def __str__(self): return self.client class Shipment(models.Model): ... num = models.IntegerField() ... What I want to do is to update the field "number_editions" (-1) every time an object "num" is created. Any idea how to do it? Thnaks -
How to implement sorting in Django Admin for calculated model properties without writing the logic twice?
In my Django model, I defined a @property which worked nicely and the property can be shown in the admin list_displaywithout any problems. I need this property not only in admin but in my code logic in other places as well, so it makes sense to have it as property for my model. Now I wanted to make the column of this property sortable, and with help of the Django documentation of the When object, this stackoverflow question for the F()-calculation and this link for the sorting I managed to build the working solution shown below. The reason for posing a question here is: In fact I implemented my logic twice, once in python and once in SQL (sort of), which is against the design paradigm of implementing the same logic only once. So I wanted to ask whether I missed a better solution for my problem. Any ideas are appreciated. This is the model (identifyers modified): class De(models.Model): fr = models.BooleanField("[...]") de = models.SmallIntegerField("[...]") gd = models.SmallIntegerField("[...]") na = models.SmallIntegerField("[...]") # [several_attributes, Meta, __str__() removed for readability] @property def s_d(self): if self.fr: return self.de else: return self.gd + self.na This is the Model Admin: class DeAdmin(admin.ModelAdmin): list_display = ("[...]", … -
Django manual control of modified-since
I have an endpoint where I usually cache the data. But I want to refresh the data every few hours. So I want to implement a condition similar to: if header.last_modified - now() > one_hour: return create_new_data_with_last_modified_set_to_now() else: return http_answer_304_not_modified() The problem is that Django's API only supports last_modifed(callback_that_gets_last_modified) that both compares the last modification time, and sets it to the same value on the HTTP response. How can I control these 2 values separately? P.S: The reason I need this is that I send some information that timeouts after X seconds. So if X/2 seconds already passed, I want to refresh it -
Why Django Showing this kind of error and how to fix it?
urls.py `from django.urls import path from.import views urlpatterns = [ path('', views.index, name='index'), path('about', views.about, name='about'), path('ourwork', views.ourwork, name='ourwork'), path('portfolio', views.portfolio, name='portfolio'), path('blog', views.blog, name='blog'), path('careers', views.careers, name='careers'), path('contact', views.contact, name='contact'), ]` views.py `from django.shortcuts import render Create your views here. def index(request): return render(request,'artsoft/index.html') def about(request): return render(request,'artsoft/about.html') def ourwork(request): return render(request,'artsoft/ourwork.html') def portfolio(request): return render(request,'artsoft/portfolio.html') def blog(request): return render(request,'artsoft/blog.html') def careers(request): return render(request,'artsoft/careers.html') def contact(request): return render(request,'artsoft/contact.html') ` sccreen short [The Error page][1] but when i clicking on blog this is work [Blog page][2] [views.py][3] [urls.py][4] [directories of files][5] [1]: https://i.stack.imgur.com/VqXzq.png [2]: https://i.stack.imgur.com/gKTrd.png [3]: https://i.stack.imgur.com/VgWIM.png [4]: https://i.stack.imgur.com/Rckvp.png [5]: https://i.stack.imgur.com/Ut2vw.png -
Django contact form not sending email
I have a simple contact form set up on my about page, and after filling in the fields and clicking submit, I get a "Success!" message that the email was sent. However, the email never arrives in my inbox. I've read numerous posts on here about this problem (seems to be pretty common) but everything I've tried does not work; even using django.core.mail.backends.console.EmailBackend fails to print in the console, yet I still get a "Success!" message when submitting. My settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.getenv("SECRET_KEY") DEBUG = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.live.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'xxxx@hotmail.com' EMAIL_HOST_PASSWORD = os.environ['EMAIL_PASSWORD'] ... My views.py: ... from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse from django.shortcuts import redirect from .forms import ContactForm ... class AboutPage(TemplateView): template_name = 'database/templates/about.html' def about(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['xxxx@hotmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, 'about.html', {'form': form}) def success(request): return render(request, 'success.html') My urls.py: from django.urls import path from . import views urlpatterns = [ ... path('about/', views.about, name='about'), … -
Cant connect to django process running in container with vs-code
Im having trouble connecting to a django process running inside a container spawned with vs-code. Everything seem to be working and I get the startup message for the server, but when connecting to localhost:8000, I get no response... I get a published port message when starting the container: Published Ports: 8000/tcp -> 127.0.0.1:8000 and also a clean start when starting launch.json debug System check identified no issues (0 silenced). October 13, 2019 - 17:45:05 Django version 2.2.6, using settings 'fpl-django.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Why cant I access the site on: localhost:8000? devcontainer.json: // For format details, see https://aka.ms/vscode-remote/devcontainer.json or the definition README at // https://github.com/microsoft/vscode-dev-containers/tree/master/containers/docker-existing-dockerfile { "name": "Existing Dockerfile", // Sets the run context to one level up instead of the .devcontainer folder. "context": "..", // Update the 'dockerFile' property if you aren't using the standard 'Dockerfile' filename. "dockerFile": "../docker/dev/python/Dockerfile", // The optional 'runArgs' property can be used to specify additional runtime arguments. "runArgs": [ // Uncomment the next line to use Docker from inside the container. See https://aka.ms/vscode-remote/samples/docker-in-docker for details. // "-v","/var/run/docker.sock:/var/run/docker.sock", // Uncomment the next line if you will be using a ptrace-based debugger like C++, Go, and Rust. // "--cap-add=SYS_PTRACE", … -
How can I upgrade pip version in cloud foundry for python buildpack
I am trying to host a django application on cloud foundry. I am getting error: "You are using pip version 9.0.1, however version 19.2.3 is available. You should consider upgrading via the 'pip install --upgrade pip' command." Now, how can I upgrade pip version for my application in cloud foundry environment I tried mentioning buildpack in manifest.yml from: https://github.com/cloudfoundry/python-buildpack Manifest.yml file applications: - name: app command: python manage.py runserver buildpack: https://github.com/cloudfoundry/python-buildpack.git -
how to reassign value to a variable after doing arithmetic operations in Django Template Language (jinja2)
I want to do arithmetic operations within Django Template format and also assign the new value to the same Variable I have so far used {{with}} {{set}} and also django-mathfilters but i am unable to reassign value back to the same variable. {% with count=0 %} {% for report in reports %} <tr> <th scope="row">{{set count count|add:"1"}}</th> <td>{{report.submit_time}}</td> <td>{{report.file_name}}</td> {% if report.is_complete %} <td>Complete</td> {% else %} <td>Pending</td> {% endif %} <td>{{report.score}}</td> </tr> {% endfor %} {%endwith%} i want to show numbers in serial in my table -
Changing Django's default list of Common Password
I just try to use Django. when i try to create superuser with the createsuperuser and i try to use some common password like abcd1234 (because abc or 123 isn't allowed), it cannot accept it because apparently that my password is too common, i know that the createsuperuser use somekind of password list to match mine with theirs. I want to ask that whether it is possible to change the password list. i already tried to open manage.py to find the createsuperuser method but i didnt find it because it only contains run(sys.argv) -
Try to build tv-series & movies site with django
I am trying to build a tv series and movies site , but I can't access the Ep from Tv. I am trying to make my url look like that www.SiteName.com/friends/ep/1 but I have no idea what I should write in views.py and urls.py . this is my models.py from django.db import models class Tv(models.Model): title = models.CharField(max_length=250) slug = models.SlugField() description = models.TextField() def __str__(self): return self.title class Episode(self): title = models.CharField(max_length=250) EpisodeNumber = models.IntegerField() slug = models.SlugField() def __str__(self): return self.title