Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass variable with the json() response received from an api using JsonResponse in Django. TypeError: 'int' object is not callable
This is my function in views.py which calls the api and send the response on html page. r = requests.post(RUN_URL, data=data) return JsonResponse(r.json(), safe=False) I have a global variable 'counter' which I want to return along with that r.json(). return JsonResponse(r.json(),counter, safe=False) When I tried this code it gives me a error: TypeError: 'int' object is not callable -
Should Django query Elasticsearch or its ORM
I have a database which could be compared to the following 3 level (dummy) architecture, and I'm not sure whether query ElasticSearch (elasticsearch-dsl), or use ElasticSearch in combination with the Django ORM: models.py class City(models.Model): name = models.CharField(max_length=28) class Genre(models.Model): name = models.CharField(max_length=28) class Artist(models.Model): name = models.CharField(max_length=28) age = models.IntegerField() city = models.ForeignKey(City) genre = models.ForeignKey(Genre) class Album(models.Model): artist = models.ForeignKey(Artist) name = models.CharField() description = models.TextField() release_year = models.IntegerField() class Song(models.Model): album = models.ForeignKey(Album) name = models.CharField(max_length=28) text = models.TextField() A user is able to query in a API (DRF) view on 3M Artist' properties (age, location etc) and on 'keywords' that the Artist sings about, this is done by Elasticsearch by searching on the Album description and Song text property. Since (in my limited experience) Elasticsearch can't join indexes, the primary index I created for this view looks as follows. documents.py class ArtistDocument(Document): name = fields.KeywordField( fields = { 'raw': fields.TextField(), 'suggest': fields.CompletionField(), } ) city = fields.NestedField(properties={ 'name' : fields.KeywordField() }) genre = fields.NestedField(properties={ 'name' : fields.KeywordField() }) age = fields.IntegerField() albums = fields.NestedField(properties={ 'id': fields.IntegerField(), 'description':fields.TextField(), 'name': fields.KeywordField(), 'release_year': fields.IntegerField(), 'songs': fields.NestedField(properties={ 'id': fields.IntegerField(), 'name': fields.KeywordField(), "text": fields.TextField() }) }) My document has multiple nested … -
Can't figure out how to set Path for Cron job
I have been going through all the different cases and examples online but I really don't understand how to set the Path for my cron job. When I try to add the job I get this error: /bin/sh: 1: /usr/bin/crontab: not found adding cronjob: (671a82cf1733e868bud228e0587aec4d) -> ('1 0-23/3 * 3-10 1-7', 'management.cron.mlb_games_today') sh: 1: /usr/bin/crontab: not found I see this question has been asked a million times but any help would be greatly appreciated. Settings.py CRONJOBS = [ ('1 0-23/3 * 3-10 1-7', 'management.cron.mlb_games_today') ] -
In django-allauth: integrations with Kakao, I entered all the keys as in Documentations
KeyError at /accounts/kakao/login/callback/ 'kakao account' ** def extract_common_fields(self, data): email = data["kakao_account"].get("email") ** kakao account is not present, anyone can help, thanks in advance -
How to create Url.py and view.py for login with Apple in django?
I go through this Url for implementing login with Apple in Django. I want to implement login with Apple in my backend Django.I have gone through this Urls but not usefull Django django-allauth-installation Django django-allauth react-apple-login Sign In with apple In my case What I think I haven't created the veiw.py and some redirection url.py for apple. that's why the backend not accepting the apple auth. Is this correct? or What are the safest way to implement this? -
Django models: Defining str_method based on ordering of one-to-many relationships in reverse-relationship
I've got a model Stem which has a one-to-many relationship with the model Question (one Stem contains many Questions). I want to define the __str__ method for Question so that it returns something like "stem.title + index of the question in that stem". For example, if the Stem is called "Foo", I want the str method for all questions in that stem to return as follows: First question: "Foo-1" Second question: "Foo-2" nth question: "Foo-n" What is the best way to accomplish this? Models.py class Stem(models.Model): title = models.CharField(max_length=255) stem = models.CharField(max_length=255) class Question(Updated): stem = models.ForeignKey( Stem, related_name='question', on_delete=models.DO_NOTHING, null=True, blank=True) question = models.CharField(max_length=255) def __str__(self): return **What do I put here** -
How to run django with apache in a docker container correctly
So I'm been trying to dockerized my Django app with apache on a container and I keep getting this error Invalid command 'WSGIProcessGroup', perhaps misspelled or defined by a module not included in the server configuration I tried to install mod_wsgi with apt and pip but the result was still the same Here is my Dockerfile FROM httpd:2.4 ADD ./requirements.txt ./ RUN apt-get update \ && apt-get install -y \ python3-pip python3-venv \ libapr1 libapr1-dev \ libaprutil1-dev \ libapache2-mod-wsgi \ && python3 -m venv /.cp \ && /.cp/bin/pip install --no-cache-dir -r requirements.txt \ && rm -rf /var/lib/apt/lists/* The requirements.txt django mod-wsgi psycopg2-binary djangorestframework markdown django-filter my custom vhost file <VirtualHost *:80> serverAdmin svenikia@taskmaster.com DocumentRoot "/usr/local/apache2/htdocs/webapp" Servername www.webapp.io ServerAlias webapp.io ErrorLog "/var/log/apache2/error.log" CustomLog "/var/log/apache2/access.log" combined Alias /static /capstone/static <Directory "/usr/local/apache2/htdocs/webapp/static"> Require all granted AllowOverride None </Directory> <Directory "/usr/local/apache2/htdocs/webapp/webapp"> <Files wsgi.py> AllowOverride None Require all granted </Files> </Directory> WSGIProcessGroup webapp_project WSGIDaemonProcess webapp_project python-path=/webapp python-home=/.env WSGIScriptAlias / /usr/local/apache2/htdocs/webapp/webapp/wsgi.py </VirtualHost> And this is my docker compose file version: '2' services: postgres: image: postgres:13.1-alpine environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: parking restart: always container_name: db apache: build : ./Django image: web:1.0 container_name: web ports: - "8080:80" volumes: - ./my-httpd.conf:/usr/local/apache2/conf/httpd.conf - ./Django/web.conf:/usr/local/apache2/conf/extra/httpd-vhosts.conf - ./Django/web:/usr/local/apache2/htdocs/my-web networks: default: … -
Django best way to combine two models in a form
I have two models: class Orders(models.Model): ID = models.AutoField(primary_key=True) OrderNo = models.IntegerField('OrderNo', blank=False, null=False) Customer = models.ForeignKey('Customers', on_delete=models.DO_NOTHING) ShippingAddress = models.ForeignKey('CustomerAddresses', on_delete=models.DO_NOTHING, related_name="ShippingAddress") BillingAddress = models.ForeignKey('CustomerAddresses', on_delete=models.DO_NOTHING, related_name="BillingAddress") Items = models.ForeignKey('OrderItems', on_delete=models.DO_NOTHING) OrderStatus = models.CharField('OrderStatus', max_length=48, blank=False, null=False) Payment_Status = models.CharField('Payment_Status', max_length=128, blank=False, null=False) Created_Date = models.DateTimeField(auto_now_add=True) Updated_Date = models.DateTimeField(auto_now=True) ShippingMethod = models.ForeignKey('DeliveryMethods', on_delete=models.DO_NOTHING) PaymentMethod = models.ForeignKey('PaymentProvider', on_delete=models.DO_NOTHING) UserID = models.ForeignKey('MasterData', on_delete=models.CASCADE) class OrderItems(models.Model): ID = models.AutoField(primary_key=True) Item = models.ForeignKey('Products', on_delete=models.DO_NOTHING) Quantity = models.IntegerField('Quantity') Price = models.DecimalField('Price', max_digits=10, decimal_places=2) OrderNo = models.ForeignKey('Orders', on_delete=models.DO_NOTHING) def __str__(self): return str(self.ID) I have written an add item view where the productID is written in a session list, but how can I say in form.save() that every product in this session list should be assigned to the Items field in the Orders model? -
Scalable Inference Server for Object Detection
I have created a Django service (nginx + Gunicorn) for object detection models. For my case i have 50+ models with resnet 50 based back bone. Server Machine Specification: 16 CPU 64 GB Ram I have pre-loaded all the models in my service. I am running 20 inference requests in parallel. But issue i am facing that Gunicorn intermittently restarts any worker out of 8 workers when inference is running and it is not due to time out. it starts to reloading the model in service again. Due to this my inference requests are failing. I have notice that might be due to server's all cpus are utilised to 100%. Can you please Suggest the solution or other way to run inference as service ? -
Django parse data to model without storing
I was wondering if there is a way to parse a json to an object of the model class without having any databse interaction. If we do what I want to do without django I could serialize a Json into an object class, for example with some help of marshmallow_dataclass @dataclass class Example: id : int name : str If I do it with a django model and serializer I do it with a standard model serializer and a model class: serializer = ExampleSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() So now the question is if there is a way to do combine them. Reason for this, I have a shared model across different applications. Now since some are just processing the data, with there is no need to store it, which I currently do but is a performance drawback. At the same time with combining them I want to achieve to not have to maintain a model and a class with the same fields. Therefore how can I use the model class to parse the data to without having to store them in the database? -
Cannot Create New Users with Django
As the title states, I've been having a huge problem adding users to my Django server as of late. I was following this tutorial on setting up user registration with Django when I realized that there were no users being created when I checked the admin panel. In my forms.py file: from django import forms from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegisterForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] In my views.py file: def createUser(request): form = RegisterForm(response.POST) if request.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("/home") else: form = RegisterForm() context = {'form': form} return render(request, "main/signup.html", context) Here is a link to signup.html without all the Django functions. In signup.html, I tried three things: Replaced each <input> tags with its respective {{form.formfield}} Placed {{form}} in the next line after the <form> tag Removed all HTML, CSS, and JS from the signup page and unlinked it from the template page and made the signup page consist of only <form method="POST" action=""> {% csrf_token %} {{form.username.label}} {{form.username}} {{form.email.label}} {{form.email}} {{form.password1.label}} {{form.password1}} {{form.password2.label}} {{form.password2}} <input type="submit" name="Create User"> </form> In all three … -
jinja2 Can't slice elements
I am trying to retrieve some data from a django database. I filter through the database with a query which I use to get a query set. I then pass this set into template by setting results to the query set. {% for result in results %} <div class="card"> <div class="card-body"> <h5 class="card-title">{{result.name}}</h5> <ul class="card-text"> {% for item in (result.item_set.all)[:5] %} <li>{{item.name}}</li> {% endfor %} </ul> <a href="#" class="card-link">Go To</a> </div> </div> {% endfor %} I would like to have the first five elements of the item set. The query set holds a bunch of parent tables which have foreign keys to a different table. Think of it like I have a set of a bunch of people and I can get each person's name and all of their pets' names. Maybe someone has a lot of pets so I'd only want the first 5 of them. However, I am getting this error here that says TemplateSyntaxError at /results Could not parse the remainder: '(result.item_set.all)[:5]' from '(result.item_set.all)[:5]' I don't understand this at all since I try looking for other problems like this and they are able to use the [:5] fine. Everything works until I introduce the [:5]. -
page pops up saying that we have sent an email but nothing is sent to my email Reset Email Django
sorry for bothering,This problem has troubled me for a long time. Even if someone has an explanation, I still can't understand it. Can I explain it again in vernacular? Thank you. The problem is that a page saying that emails have been sent pops up, but I haven't received any emails! password_reset/done/ Fill in the email address and send the message: We have emailed you instructions for setting up a password. If it does not arrive after a few minutes, please check your spam folder. Indeed, a link page appears in the Terminal to notify the user to change the password, as follows: =?utf-8?b?ayBiZWxvdzpodHRwOi8vMTI3LjAuMC4xOjgwMDAvcmVzZXQvTWpVLzVwbS0zYmQ0?= =?utf-8?b?ZGZlNjUwODkzNmY3ZDBlNC8nJyc=?= From: webmaster@localhost To: aaaaaaa@hotmail.com Date: Mon, 12 Apr 2021 08:19:08 -0000 Message-ID: <161821554833.3620.8514202595356349577@DESKTOP-EV07JLF> Someone asked for password reset for email aaaaaaa@hotmail.com. Follow the link below: http://127.0.0.1:8000/reset/MjY/5pq-538bd8f15e422996d747/ Suggestions given by search in the message area: >1.For those of you facing the reset-email-sent-but-not-received issue. Make sure the email address, which you're entering into the reset field, actually belongs to a registered user. The clue is in the success message: "... if an account exists with the email you entered." So, if you're entering your own email address as a test, make sure you register a user with … -
Explain me please this asgi application
async def app(scope, receive, send): headers = [(b"content-type", b"text/html")] await send({"type": "http.response.start", "status": 200, "headers": headers}) await send({"type": "http.response.body", "body": scope["raw_path"]}) I do not understand the function applied in this asgi app. I am new to this. -
Filtering 2 values on a field
This should be pretty simple. I want to select only products which have an empty value for current_price or a value of '0.00' Here's what I have: product_list = Product.objects.filter(current_price__in=['0.00', None]) -
One form for two models in django
Django==3.1.7 django-crispy-forms==1.11.2 I 've 2 models: Order and OrderList Order is a header and OrderList is a tabular section of the related Order class Order(models.Model): print_number = models.PositiveIntegerField( verbose_name=_("Number"), default=get_todays_free_print_number, ) # ... some other fields class OrderList(models.Model): order = models.ForeignKey( Order, blank=False, null=False, on_delete=models.CASCADE ) item = models.ForeignKey( Item, verbose_name=_("item"), blank=True, null=True, on_delete=models.CASCADE ) # ... some other OrderList fields The question is how to create a form containing both models and provide the ability to add an OrderList positions within an Order into the form and save them both. What I did: forms.py - I used inline formset factory for the OrderList from django.forms import ModelForm from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from .models import Order, OrderList class OrderForm(ModelForm): class Meta: model = Order fields = [ '__all__', ] class OrderListForm(ModelForm): class Meta: model = OrderList fields = [ '__all__', ] class OrderListFormSetHelper(FormHelper): """Use class to display the formset as a table""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.template = 'bootstrap4/table_inline_formset.html' # I am not sure we should add a button here #################################################### self.add_input(Submit('submit', 'Submit', css_class='btn btn-primary offset4')) views.py @login_required def orders(request): template = f'{APP_NAME}/index.html' list_helper = OrderListFormSetHelper() list_formset = inlineformset_factory(Order, OrderList, OrderListForm,) if request.method == … -
django - autofill inline formset field in createview
I have a create view that allows the user to create a project. Within this create view I'm using an inlineformset to allow the user to set the Priority of the project. The priority has three values, foreach of these values the user can enter a score which is saved with the project. Where I am currently at is the user can enter a score & select which Priority it relates to from a drop down & then save the project with it. What I'm trying to do is have the Priority automatically set & just show the Score field without having to have the user select from the dropdown to show which one it relates to. I want the Priority to be a label & just show score field under it. Is this something that's possible to do? Current: Goal: Priority (Dropdown) Priority (Label) Score (Charfield) Score (Charfield) Views.py class ProjectCreateview(LoginRequiredMixin, CreateView): model = Project form_class = ProjectCreationForm login_url = "/login/" success_url = '/' def get_context_data(self, **kwargs): PriorityChildFormset = inlineformset_factory( Project, ProjectPriority, fields=('project', 'priority', 'score'), can_delete=False, extra=Priority.objects.count(), ) data = super().get_context_data(**kwargs) if self.request.POST: data['priorities'] = PriorityChildFormset(self.request.POST) else: data['priorities'] = PriorityChildFormset() return data def form_valid(self, form): context = self.get_context_data() prioritycriteria … -
how to passing variable from the Django views.py to another Python file?
views.py ... from app.camera import VideoCamera from app.camera import VideoCameraImage ... def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_image(request): return StreamingHttpResponse(gen(VideoCameraImage()),content_type='multipart/x-mixed-replace; boundary=frame') def image(request): url = request.GET.get('image_url') print(url) return render(request,'image.html') camera.py class VideoCameraImage(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): src2=cv2.imread(os.path.join(settings.BASE_DIR,'img/smile.png'),-1) status, frame = self.video.read() face, confidence = cv.detect_face(frame) ... ret,jpeg=cv2.imencode('.jpg',frame) return jpeg.tobytes() When the user clicks the button, the url changes for each button. I would like to receive url from def image of views.py and deliver url to camera.py in the same path. how to passing variable from the django views.py to another Python file? -
Django: Use blocks in multiple places inside template
This is the template I've written {% extends 'base.html' %} {% load static %} {% block body %} <div class="row hide-on-mobile" style="height: 100vh"> <div class="col-auto p-5"> <img src="{% static 'logo.svg' %}" class="mb-5 hide-on-mobile" style="height: 84px"/> {% block form %} {% endblock %} </div> <div class="col bg-brown p-5"> <div class="d-flex flex-column justify-content-between" style="height: 100%"> <h1 class="text-blue mb-3">It's always Ups<br>and Downs</h1> <img src="{% static 'investing_illustration.svg' %}" class="auth-illustration"/> </div> </div> </div> <div class="hide-on-desktop" style="height: 100vh; position: relative"> <div class="d-flex flex-column bg-brown h-100 p-3 align-items-start"> <img src="{% static 'logo.svg' %}" class="mb-3 hide-on-desktop" style="height: 56px"/> <p class="text-blue mb-3">It's always Ups<br>and Downs</p> <img src="{% static 'investing_illustration.svg' %}" class="auth-illustration"/> </div> <div style="position: absolute; bottom: 0; z-index: 99; background: white; width: 100%"> <div class="d-flex flex-column p-4"> <p class="mb-4">Login</p> {% block form %} {% endblock %} </div> </div> </div> {% endblock %} I inherit this template in a page as follows: {% extends 'auth_base.html' %} {% block form %} <p class="mb-4">Login</p> <form class="pb-5"> <input type="text" class="form-control" name="email" placeholder="Enter your email"> <input type="password" class="form-control" name="password" placeholder="Enter your password"> <a class="text-blue">Forgot Password?</a> <button type="submit" class="mt-3 btn btn-primary full-width">Login</button> </form> <div class="text-center"> <span>New Here? <a class="text-blue">Create an account</a></span> </div> {% endblock %} The form block is used two times..because when I inherit … -
how to send image from django server to react native?
Currently, I send an image to django from react-native through my API, then save a new image on django. I would like to send that image back as a response to the API request. Currently I have tried to convert the image to base64 and send that back, but then I get an error on my iPhone that PayloadTooLargeError: request entity too large Here is where the request is processed and response is sent back to the client: @api_view(['POST']) @permission_classes((AllowAny,)) def predict(request): try: file = request.data['file'] # print("FILEPATH FUCKER", file.get('uri').temporary_file_path()) except KeyError: return Response({'file': ['no file']}, status=HTTP_400_BAD_REQUEST) result = predictCentering(file.temporary_file_path()) return Response(result, status=HTTP_200_OK) And this is where the result comes from: cv2.imwrite("saved.jpeg", img) with open("saved.jpeg", "rb") as image_file: # noqa image_data = base64.b64encode(image_file.read()).decode('utf-8') cv2.destroyAllWindows() return [center_props, image_data] center_props works fine, image_data does not. Any help is greatly appreciated. -
Sending value from FormView form_valid() to success_url without using url
How to send this value to success_url? class AnyView(FormView): ... success_url = reverse_lazy('success') def form_valid(self, form): ... value = 'blablabla' # <<< How to pass this value? messages.success(self.request, f'Sua matrícula foi realizada.') return super(AnyView, self).form_valid(form) success.html {{ value }} I don't want to send it by url path('anyform', AnyView.as_view(), name='anyform'), -
form.is_valid() not working as intended django
I am neew to django and I am trying to make an attendance system where the user can type their name and press clock in or clock out but when I test the code. But whenever I type a name and press clock In it does not save the name and time to the database. views.py: def home(response): form = CreateNewList() empName = employeeName.objects.all if response.method == "POST": form = CreateNewList(response.POST) if 'clockIn' in response.POST: if form.is_valid(): n = form.cleaned_data["name"] now = datetime.now() current_time = now.strftime("%H:%M:%S") t = Name(name = n, timeIn=current_time) t.save() return redirect('/') else: form = CreateNewList() return render(response, "main/home.html", context={"form":form, "empName":empName}) models.py: class employeeName(models.Model): employee = models.CharField(max_length=200) total_Hours_Worked = models.CharField(max_length=8, default="Empty") def __str__(self): return self.employee class Name(models.Model): name = models.ForeignKey(employeeName, null=True,on_delete=models.CASCADE) timeIn = models.TimeField() timeOut = models.TimeField(default=datetime.now()) date = models.DateField(auto_now=True) def __str__(self): return str(self.name) forms.py: class CreateNewList(forms.ModelForm): def __init__(self, *args, **kwargs): super(CreateNewList, self).__init__(*args, **kwargs) self.fields['name'].widget = TextInput() class Meta: model = Name fields = ['name'] home.html: <label>Enter Your Full Name:</label> {{form.name}} <datalist id="attendance"> {% for empName in empName %} <option value="{{empName.employee}}"> {% endfor %} </datalist> <button type="submit" name="clockIn" value="clockIn" class="btn btn-outline-primary">Clock In</button> I tried testing whenever I press the clockIn button to print something in the terminal … -
Django project run manage.py results in no module named django
I was working on a django project served as a backend for a small personal site, the built-in localhost server by django runs smoothly until I accidentally removed the app execution alias of python in windows 10(It just happened after done that, might not be the culprit). the situation is that when I use manage.py, it always results in a no module named "django" (venv) C:\Users\hongl\PycharmProjects\fluentdesign>manage.py runserver Traceback (most recent call last): File "C:\Users\hongl\PycharmProjects\fluentdesign\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\hongl\PycharmProjects\fluentdesign\manage.py", line 22, in <module> main() File "C:\Users\hongl\PycharmProjects\fluentdesign\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHO NPATH environment variable? Did you forget to activate a virtual environment? I tried to resolve it a bit and was only baffled to find the terminal, with which the venv had already been activated, was always being attached to the system-wise python when running which has no django installed in it. The following is python console from venv: (venv) C:\Users\hongl\PycharmProjects\fluentdesign>python Python 3.8.9 (tags/v3.8.9:a743f81, Apr 6 2021, 14:02:34) [MSC … -
How to avoid n+1 queries in Django when you are not able to use select_related?
This is a problem I encounter quite often. Lets say I have three models: class CourseType(models.Model): name = models.CharField(max_length=50) class CourseLevel(models.Model): name = models.CharField(max_length=50) course_type = models.ForeignKey(CourseType, on_delete=models.CASCADE) class Course(models.Model): name = models.CharField(max_length=50) course_level = models.ForeignKey(CourseLevel, on_delete=models.CASCADE) def __str__(self): return "{}-{}: {}".format(self.course_level.course_type.name, self.course_level.name, self.name) If I were to iterate over Course.objects.all() and print the Course objects, that would be a n+1 query. This is easily solved by using select_related: Course.objects.select_related('course_level', 'course_level__course_type') The problem with this is I have to remember to use select_related every time. Its also ugly, especially if you have another model in there, like CourseDetails. One solution to this is to use a custom manager: class CourseManager(models.Manager): def with_names(self): return self.select_related('course_level', 'course_level__course_type') I can then use Course.with_names.all() and no longer need to add in the select_related every time. This has a major limitation - I can only take advantage of the manager when directly using Course. Very often I will iterate over Course objects through foreign keys, and again I will need to remember to use select_related and litter it all over my code. An example: class Student(models.Model): name = models.CharField(max_length=50) class StudentCourseEnroll(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) Now if I want to print … -
Django project Page not Found
I am trying the basic Django tutorial: https://docs.djangoproject.com/en/3.1/intro/tutorial01/ The admin page is up and running but getting a 404 on the http://localhost:8000/polls/ page: I cannot understand what this code is doing: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls) ] I didn't define any polls.urls, so how will it know how to route the request? Total beginner here. Coming from the old Tomcat/JBoss world.