Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SocketIo integration with Django
I have been trying to integrate socketio with Django, And I am getting the following error. [31/Mar/2020 14:50:27] "GET /socket.io/?EIO=3&transport=polling&t=N4n4ds4&b64=1 HTTP/1.1" 200 117 [31/Mar/2020 14:50:27] "POST /socket.io/?EIO=3&transport=polling&t=N4n4dsj&b64=1&sid=9053be92266c46148304c09833b2ebe8 HTTP/1.1" 200 2 Traceback (most recent call last): File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/django/contrib/staticfiles/handlers.py", line 68, in __call__ return self.application(environ, start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/engineio/middleware.py", line 60, in __call__ return self.engineio_app.handle_request(environ, start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/socketio/server.py", line 558, in handle_request return self.eio.handle_request(environ, start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/engineio/server.py", line 377, in handle_request environ, start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/engineio/socket.py", line 108, in handle_get_request start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/engineio/socket.py", line 152, in _upgrade_websocket return ws(environ, start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/engineio/async_drivers/eventlet.py", line 16, in __call__ raise RuntimeError('You need to use the eventlet server. ' RuntimeError: You need to use the eventlet server. See the Deployment section of the documentation for more information. [31/Mar/2020 14:50:27] "GET /socket.io/?EIO=3&transport=websocket&sid=9053be92266c46148304c09833b2ebe8 HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 52220) Traceback (most recent call last): File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/Users/murali/yourenv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/murali/yourenv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: … -
How to deploy bootstrap theme "QuixLab" in django?
I know similar questions have been answered before but believe me this is not replication. I have gone through each and every bit of answer but not able to solve my problem. I am just trying to deploy a bootstrap theme in django. I have done everything, that should be done but still css and jquery is not getting picked up in html forms. Settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] index.html , all links have been set like these: <link href="{% static 'assets/css/lib/font-awesome.min.css' %}" rel="stylesheet"> <link href="{% static 'assets/css/lib/themify-icons.css' %}" rel="stylesheet"> <link href="{% static 'assets/css/lib/menubar/sidebar.css' %}" rel="stylesheet"> <link href="{% static 'assets/css/lib/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'assets/css/style.css' %}" rel="stylesheet"> <script src="{% static 'assets/js/lib/owl-carousel/owl.carousel.min.js' %}"></script> <script src="{% static 'assets/js/lib/owl-carousel/owl.carousel-init.js' %}"></script> <script src="{% static 'assets/js/scripts.js"></script> Everything is in its place but css is not getting picked up while I have seen that all images are getting picked up that means static folder is getting accessed properly. When I see terminal, I finds lines like these: [31/Mar/2020 20:10:44] "GET /static/assets/js/lib/weather/jquery.simpleWeather.min.js HTTP/1.1" 404 1773 [31/Mar/2020 20:10:44] "GET /static/assets/js/lib/weather/weather-init.js HTTP/1.1" 404 1737 [31/Mar/2020 20:10:44] "GET /static/assets/js/lib/owl-carousel/owl.carousel.min.js HTTP/1.1" 404 1764 [31/Mar/2020 20:10:44] "GET /static/assets/js/lib/owl-carousel/owl.carousel-init.js HTTP/1.1" 404 1767 For testing, I deploy another … -
Updating the axis of a highcharts chart object using jquery after inital render (django)
I can seem to figure out a basic question I’ve got a highcharts chart in my django app that is getting loaded in the template. The data for the chart is getting populated via ajax. I’d like to add a button above the chart which if clicked toggles the axis to logarithmic (instead of the default, linear) but I can’t seem to make this work Here’s my code HTML <button id="target" type='button' > switch to log </button> <div id="container1" style="width:100%; height:400px;"></div> Javascript <script> $(document).ready(function() { var chartOptions = { chart: { renderTo: 'container1', type: 'line', }, title: {text: null}, xAxis: {title: {text: null}, labels: {rotation: -45}}, yAxis: {title: {text: 'Item counts'}, type: 'linear', stackLabels: {enabled: true}, }, plotOptions: {column: {dataLabels: {enabled: false}, stacking: 'normal'}}, series: [{}], }; var chartDataUrl = "{% url 'global_trend_chart' %}" ; $.getJSON(chartDataUrl, function(data) { chartOptions.xAxis.categories = data['chart_data']['date']; chartOptions.series[0].name = 'Global counts'; chartOptions.series[0].data = data['chart_data']['item_counts']; var chartA = new Highcharts.Chart(chartOptions); }); $( "#target" ).click(function() { chartA.update({ yAxis: { type: 'logarithmic', } }); }); } ); </script> I appreciate the help -
I can't add a record from the django form into a database
I have this function in views.py file that responsible for adding a record into the Database def add_academy(request,pk): child = get_object_or_404(Child_detail, pk=pk) academic = Academic.objects.get(Student_name=child) form = AcademicForm(request.POST, instance=academic) if form.is_valid(): form.save() return redirect('more',pk=pk) #it will redirect but can't create a new record else: form=AcademicForm() context = { 'academic':academic, 'child':child, 'form':form, } return render(request,'functionality/more/academy/add.html',context) And here is my form.py file class AcademicForm(forms.ModelForm): class Meta: model=Academic fields='Class','Date','Average_grade','Overall_position','Total_number_in_class' labels={ 'Average_grade':'Average Grade', 'Overall_position':'Overall Position', 'Total_number_in_class':'Total Number In Class' } Date = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ) ) And here is my model.py file class Academic(models.Model): Student_name = models.ForeignKey(Child_detail,on_delete = models.CASCADE) Class = models.CharField(max_length = 50) Date = models.DateField() Average_grade = models.CharField(max_length = 10) Overall_position = models.IntegerField() Total_number_in_class = models.IntegerField() def __str__(self): return str(self.Student_name) And also this is my template will be used to display form <div class="card-body"> <form action="" method="POST" autocomplete="on"> {% csrf_token %} <div class="form-group"> {{form | crispy}} <input type="submit" value="Save" class="btn btn-primary btn-block"> </form> </div> -
How do I redirect away from the login page, if the user is already logged in and goes to login page in Django?
I'm using built in authentication system of Django 2.1. Example Case: User logs in by providing his credentials, once he is directed to the home page and presses browser's back button he'll land in the login page again. It'll again ask for the credentials but actually the user is already logged in. How do we redirect the user to the home page in this case? -
Slider in django website using bootstrap4 carousel
i want to create a carousel slider in my django website where i could easily add/remove images from my admin panel. <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner"> {% for obj in projects %} {% if forloop.first %} <div class="carousel-item active "> {% else %} <div class="carousel-item "> {% endif %} <img class="d-block w-100 h-50" class="h-50 d-inline-block" src="{{ obj.thumbnail.url}}" alt="{{obj.title}}"> </div> {% endfor %} </div> -
django_session table is not found after making migrations?
enter image description here I changed model and deleted migrations, pycache folders as well sqlite db file of the application in the project. then tried python manage.py makemigrations appname python manage.py migrate appname -
issue with rendering chart with django and chart.js
I am learning how to integrate charts in django app with chart.js as well as the rest framework from django and I am running into an issue that I have no clue how to go about. when running the server, I don't any error, simply a blank page and I cannot figure out why my chart is not displaying. Here attached my html page, view.py and urls.py because I think that the issue is somewhere in here! from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from .models import top_sellers, Classification, ClassificationSerializer,stock_anormal, stock_negatif, niveau_service from django.views.generic import View from django.http import JsonResponse class HomeView(View): def get(self, request, *args, **kwargs): return render(request, 'dashboard/base.html', {}) def get_classification(request, *args, **kwargs): labels = ["red", "blue"] data = { 'labels' : labels, 'class' : ['AA, A'], 'inventory_dollars' : [12,15]} return JsonResponse(data) {% extends 'dashboard/base.html' %} <script> {% block jquery %} var endpoint= '/class/' var defaultData = [] var labels = ["red", "blue"] $.ajax({ method: "GET", url: endpoint, sucess: function(classification){ labels = data.labels defaultData = data.defaul console.log(data) }, error: function(error_data){ console.log("error") console.log(error_data) } }) var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: '# of … -
Django - Images aren't loading in second app
I got two apps 1. main, 2. contact inside my Django project. Both use the base.html file to get the head and the footer. Inside the footer is a image which perfectly work in the main app but inside the contact app it is not shown, there is no images displayed. I tryed to change the settings but everything was set correct. I implement the static and media root STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and inside the urls.py I do urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('contact/', include('contact.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) If i open the inspector in firefox the path is the right one but the console throws a 404 GET http://localhost:8000/static/media/contact/contact_image.jpg 404 (Not Found) How couldnt it work when the media folder is in the root of the app and the settings are the same in both apps? -
Samesite error in Django app while using Datatables Cloudflare CDN file
Can someone tell me how to resolve the warning/error on my django site? A cookie associated with a cross-site resource at http://datatables.net/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032. 127.0.0.1/:1 A cookie associated with a cross-site resource at http://cloudflare.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032. 127.0.0.1/:1 A cookie associated with a cross-site resource at https://cloudflare.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032. (index):329 Uncaught ReferenceError: $ is not defined at (index):329 Console Log -
Django merging between two querysets by adding an element from one queryset to the other every nth element
Assume I have in my model "movies" of several types: E.g.: Action, Drama, Fantasy etc... In my template I would like to list the 50 most recent movies (sorted by date). Which is rather straight forward E.g.: Movies.order_by('-date')[0:50] However, I have an additional requirement: I would like to list Action movies (sorted by date) every 3 movies of other types: E.g.: (0) Drama 12/3 (1) Adventure 11/3 (2) Science 10/3 **(3) Action 11/3** (4) Sci-Fi 9/3 (5) Sci-Fi 8/3 (6) Adventure 4/3 **(7) Action 8/3** (8) Drama . . . (50) ... In other words, merge two query sets: movies sorted by date of all movies excluding action movies. movies sorted by date of only actions movies. The new query set (or list?) should be 3 items from the first query set and 1 item from the other query set. -
Visual Studio - Error: Unable to download installation files
I'm following a nice tutorial on hosting Django on Apache, for that I need to install mod_wsgi using pip. This needs c++ 14.0 or higher .. I've been trying to install visual studio community edition and it's tools using the microsoft installer. However, a bugging error keeps chacing me: "Unable to download installation files. Check your internet connection and try again" Now my internet connection is fine, I also did many attempts to restart, and re-download - cmd commands for offline installation and many many attempts. I need help here as It is driving me crazy!:D can anybody please help? all the best -
How to access ForeignKey child model's ID? int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method
i keep getting error: Line number: 1 - int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' Im trying to access the child models id to sort by the company instance for each store. It works if i upload the data through the child model but trying to do the opposite throws errors? model.py class Parent(models.Model): store = models.IntegerField(primary_key=True) state = models.CharField(max_length=250, blank=True) # pylint: disable=R0903 def __str__(self): return '{}'.format(self.store) class Child(models.Model): id = models.BigIntegerField(primary_key=True) store = models.ForeignKey('Parent', on_delete=models.CASCADE, null=True) company = models.CharField(max_length=250, blank=True) rank = models.IntegerField(blank=True, default='') # pylint: disable=R0903 def __str__(self): return '{}'.format(self.company) admin.py class ParentResource(resources.ModelResource): state = fields.Field(attribute='state', column_name='State') store = fields.Field(attribute='store', column_name='Store') company = fields.Field(attribute='company', column_name='Company', widget=ForeignKeyWidget(Child, 'company')) class Meta: model = Parent import_id_fields = ('store', 'state',) fields = ('store', 'state', 'company',) def before_import_row(self, row, **kwargs): company = row.get('Company') store = row.get('Store') store = Parent.objects.get_or_create(store=store) rank = row.get('Rank') company = Child.objects.get_or_create(store=store[0], company=company, rank=rank, id=id) class ParentAdmin(ImportExportModelAdmin): inlines = [ChildInline] resource_class = ParentResource list_display = ['store', 'state'] class Meta: model = Parent -
Django overwrite header value in request object
I am writing middleware that, when it receives a request containing a header 'foo', modifies its value, before passing the request on. Django makes direct assignment illegal, so these do not work: request.headers['Foo'] = 'bar' request['Foo'] = 'bar' I do have a working solution, but it's a bit hacky: request.headers.__dict__['_store']['foo']=('Foo','bar') Is there a cleaner way of doing it that I've missed? -
Keep a list of users who accessed specific url in model
What I'm trying to do is every time a user visits a URL related to the object, a viewed_by field gets updated with that specific user's ID number. I've had a look at this documentation but I feel like it doesn't really fit exactly what I need. I'm not sure about the implementation, which is why I'm asking this question, but this is how I'd imagine it or something like this. class Documents(models.Model): document = models.FileField(upload_to=my_upload) document_name = models.CharField(max_length=100) document_viewed_by = ??? #ids of each user that viewed the document -
annotate with RawSQL by entry
Is it possible to get the query of the RawSQL to work with one entry at a time? I'll give an example of my problem: I have a DateRangeField in a model (it's a Postgres field) date = DateRangeField(null=True) What I'm aiming to get is the days inside the range. I tried doing the next Django ORM query models.my_model.objects.annotate(diff_days=RawSQL("""SELECT UPPER(date)-LOWER(date) FROM my_model_db_name""",[])) Which of course led to the following error (because the query FROM is the whole table) django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression and that's because RawSQL is expecting a single result (e.g. put SUM or COUNT in the SELECT expression) and that's because of the query executed by the entire table instead of the current object. Is there a way to implement it into Django ORM? The other solution is, of course, to get the executed result and then calculate it by raw. -
HOW TO REDIRECT TO ANOTHER PAGE THAT CONTAINING ID IN DJANGO
I have this function in view.py file that i pass an ID on it and it render a certain page def more_about_child(request,pk): child = get_object_or_404(Child_detail,pk=pk) academic = Academic.objects.filter(Student_name=child) context={ 'child':child, 'academic':academic, } return render(request,'functionality/more/more.html',context) And this urls.py file belongs to above views.py file from . import views from django.urls import path urlpatterns=[ #more_about_child path('more/<int:pk>/',views.more_about_child,name='more'), ] Then i have this function that i want to redirect to a page that contain an id in the above urls.py file def add_academy(request,pk): child = get_object_or_404(Child_detail, pk=pk) academic = Academic.objects.get(Student_name=child) form = AcademicForm(request.POST, instance=academic) if form.is_valid(): form.save() return redirect('more') #it fails to redirect to this url,because it contain an ID in it else: form=AcademicForm() context = { 'academic':academic, 'child':child, 'form':form, } -
remove None variable from Object filter
remove None variable from Object filter i have many variable for search with object filter Some of this variable is None how i can handle this variable from objects filter, None variable remove from object filter for example: centerLat = request.GET.get('centerLat') centerLng = request.GET.get('centerLng') typeCheck = request.GET.get('typeCheck') typeCheck2 = request.GET.get('typeCheck2') typeCheck3 = request.GET.get('typeCheck3') myfilters = myobject.objects.filter(lat=centerLat, lng=centerLng, type1=typeCheck, type2=typeCheck2) i need if variable is none dont use in objects filter -
django2.11 QuerySet.dates use kind as "week" not returns a list of all distinct year/week values
Environment: Win10 + python3.6.8 + django2.11 I have a query: models.DpoOps.objects.dates('start_time', 'week') In it's document, "week" returns a list of all **distinct** year/week values for the field. All dates will be a Monday. -- https://docs.djangoproject.com/en/2.2/ref/models/querysets/#django.db.models.query.QuerySet.dates But in my practice, if I use 'week' as kind, it's result isn't unique, it has repeated-returns. i.e. models.DpoOps.objects.dates('start_time', 'year') <QuerySet [datetime.date(2020, 1, 1)]> models.DpoOps.objects.dates('start_time', 'month') <QuerySet [datetime.date(2020, 2, 1), datetime.date(2020, 3, 1)]> models.DpoOps.objects.dates('start_time', 'day') <QuerySet [datetime.date(2020, 2, 26), datetime.date(2020, 3, 2), datetime.date(2020, 3, 3), datetime.date(2020, 3, 4), datetime.date(2020, 3, 5), datetime.date(2020, 3, 9), datetime.date(2020, 3, 16), datetime.date(2020, 3, 17), datetime.date(2020, 3, 18), datetime.date(2020, 3, 19), datetime.date(2020, 3, 29)]> models.DpoOps.objects.dates('start_time', 'week') <QuerySet [datetime.date(2020, 2, 24), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), datetime.date(2020, 3, 2), '...(remaining elements truncated)...']> Did i misunderstand it's means? -
customize the get_payload function in django-graphql-jwt
please, how can I customise the get_payload function in django-graphql-jwt? def get_payload(token, context=None): try: payload = jwt_settings.JWT_DECODE_HANDLER(token, context) except jwt.ExpiredSignature: raise exceptions.JSONWebTokenExpired() except jwt.DecodeError: raise exceptions.JSONWebTokenError(_('Error decoding signature')) except jwt.InvalidTokenError: raise exceptions.JSONWebTokenError(_('Invalid token')) return payload -
Django 3.0 secondary app - Not Found: static files
Situation I have a django 3.0 application, I have built a few apps already in it that are functioning. That I have tried to create an authentication app for signup, login. The backend for the signup and login works. But the static files like .js, .css, images are not appearing. I also have a base.html file that contains all style sheet import and javascript imports that extends to this signup.html somehow if I fill up the signup.html file with nothing but just putting the extensions from the base.html file it still gives me the same errors Folder Strudture mainapp-project mainapp (this is where I keep a base.html file that extends to the ) secondapp (base.html file extends here) settings.py #actual folder name where we save our images STATICFILES_DIRS = [os.path.join(BASE_DIR, 'mainprojectfolder/static/')] # Removed based on: https://stackoverflow.com/questions/60354519/django-base-html-extended-to-homepage-html-static-images-appear-but-home-css-d STATIC_ROOT = os.path.join(BASE_DIR, 'static') #this_is_what_U_see_in_URL_bar_for_static_files STATIC_URL = '/static/' base.html <!doctype html> <html lang="en"> {% load static %} <!-- SYLES & BASICS--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/> <title> </title> <link rel="canonical" href="https://getbootstrap.com/docs/4.3/examples/carousel/"> <link rel="stylesheet" href="static/css/bootstrap/bootstrap.min.css"> <!-- --> <link href="static/css/style.min.css" rel="stylesheet"> </head> <body> <header> ... </header> {% block content %} {% endblock %} <script src="static/public/js/jquery/jquery.min.js"></script> … -
In django rest framework, How to get queryset of foreignkey instead of url?
In models: class Brand(models.Model): name = models.CharField() class Product(models.Model): price= models.CharField() brand = models.ForeignKey(Brand) In serializers, I use hyperlink and in views, I use viewset and also in urls I use routers. As output in API, in Product url i get the Product queryset and the value of brand is a url link. But i want the queryset of Brand in Product queryset. How can it possible? For frontend I use axios, when i get a request in Product queryset here I also get url for Brand because of foreignkey. I need to access the queryset of Brand when I send get request for Product url. How can I do that? -
Django: get all distinct values from attribute in db
So I have a model "site" which has an attribute country. I need an endpoint that fetches all countries I have following filter in my view: countries = Site.objects.order_by().values("country").distinct() This returns a queryset. What's the best way to return this data? A serializer uses a model, right? But this is just a queryset of strings.. -
if-else statement in python django
I am new to Django and I have a problem that I couldn't solve. I am trying to display a specific question and other related attribute from my Question model based on a field from the Participant model. The issue here is that it directly goes to the else statement even when the condition is true.I tried to print(participant.condition) and it works so I am not sure why its not working with the if statement. @login_required def LPSC_VIEW1(request): participant=request.user.participant if participant.condition == 'LPN': First_question= Question.objects.get(id=1) all_choices = First_question.choices.all() context = {'First_question': First_question, 'all_choices': all_choices} return render(request, 'study/FirstQN.html', context) else: First_question= Question.objects.get(id=12) all_choices = First_question.choices.all() context = {'First_question': First_question, 'all_choices': all_choices} return render(request, 'study/FirstQSC.html', context) my models as the following: class Question(models.Model): question_text = models.CharField(max_length=200) caption = models.CharField(max_length=200, default="this is a caption") choices = models.ManyToManyField(Choice) vis_image = models.ImageField(default= "this is an image", null=False, blank=False, upload_to="static/study/img") def __str__(self): return self.question_text class Condition(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Participant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) condition = models.ForeignKey(Condition, on_delete=models.CASCADE) score = models.IntegerField(default=0) def __str__(self): return self.user.username -
NoReserveMatch and Error during template rendering
i am new at this thing. first, this is my urls.py urlpatterns = [ path('results/<int:id>/', views.abstract, name='abstract'), path('results/', views.result, name='result'), path('', views.index, name='index'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and my wiews def index(request): return render(request, 'online_sp/index.html') def result(request): script = Main() data = script.json_dt if 'No result' in data.keys(): no_result = True return render(request , 'online_sp/scripts.html', {'no_result':no_result}) else: return render(request , 'online_sp/scripts.html', data) def abstract(request, id): return render(request , 'online_sp/abstract.html') my goal is get page results/1/ with a button click from results/' page. (script.html) <a style="margin-left: 10%;" class="btn btn-dark" href="{% url 'abstract' 1%}" role="button">Abstratc</a> but it gives the NoReverseMatch error and says there is a error at line 0 in base.html which is a header template. NoReverseMatch at /results/ Error during template rendering In template C:\MyPythonScripts\not_a_vlog\online_sp\templates\online_sp\base.html, error at line 0 Reverse for 'abstract' with no arguments not found. 1 pattern(s) tried: ['results/(?P<id>[^/]+)/$'] 1 <!doctype html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="utf-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1, 7 shrink-to-fit=no"> 8 <title>{% block title %}Search Similar Papers{% endblock title %}</title> 9 </head> 10 but when i change path('results/<int:id>/', views.abstract, name='abstract') to path('<int:id>/', views.abstract, name='abstract') it gets the results/ page with abstract's template. however, i should go results/ page first and …