Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django add image to login template
I have a image, I have to place this image at login.html template, where my login.html is in a app called pages. login.html !DOCTYPE html> <html> <head> <title>Login</title> </head> <body> {% if form.errors %} <p>Invalid inputs</p> {% endif %} {% if next %} <p>Pleas login to continue</p> {% endif %} <div> <form method="post" action="{% url 'login' %}"> {% csrf_token %} <p>Username: {{ form.username }} </p> <p>Password: {{ form.password }} </p> <p><input type="submit" value="Log in"> <input type="hidden" name="next" value="{{ next }}"> <button onclick="location.href={% url 'pages:register' %}" type="button">Sign up</button> </p> </form> </div> <a href="{% url 'social:begin' 'google-oauth2' %}"> <img src="google_sign_in.png" alt="Google Sign in"> </a> </body> </html> So where should I place my image file so I can access it my login.html file and what should be src='' for image -
NoReverseMatch at / Reverse for 'snippet_detail' with arguments '('1534691562.8842607',)' not found
I'm trying to create a snippet in a django application. I'm getting the following error when creating the snippet NoReverseMatch at / Reverse for 'snippet_detail' with arguments '('1534693093.896782',)' not found. 1 pattern(s) tried: ['(?P<snippet_slug>[\\d]+)$'] I'm unable to figure out the issue. Everything in url patterns and views looks ok. But the error still exists. django_project/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('djangobin.urls')) ] djangobin/urls.py urlpatterns=[ url(r'^$', views.index, name='index'), url('^(?P<snippet_slug>[\d]+)/$', views.snippet_detail, name='snippet_detail'), ] djangobin/views.py def index(request): if request.method=='POST': f=SnippetForm(request.POST) if f.is_valid(): snippet=f.save(request) return redirect(reverse('djangobin:snippet_detail', args=[snippet.slug])) else: f=SnippetForm() return render(request, 'djangobin/index.html',{'form':f}) def snippet_detail(request, snippet_slug): snippet = get_object_or_404(Snippet, slug=snippet_slug) snippet.hits += 1 snippet.save() return render(request, 'djangobin/snippet_detail.html', {'snippet': snippet}) -
I am unable to create a django website in PyCharm. I am getting a syntax error, tough I am following the steps from the tutorial
I am very new to the whole python ecosystem and I am trying in learning on my own. I am using PyCharm and I want to get familiar with django framework. I installed django, and as shown in the image, and if I call the get_version() method it gives me the version 2.1 That's what I was told here. The next step, as they say here, is to create a project with the command: $ django-admin startproject mysite And here I am getting a syntax error. Django is installed, I am using python 3.7 which should be fine, but I don't get the problem. It may be some tiny detail that I am missing. Any help will be appreciated! -
Two Domains for a Gunicorn.service
I got one domain (domain.com) and one sub domain (subdomain.domain.com) each running Django with Gunicorn and Nginx. My question is how do I setup Gunicorn.service to include the two domains. Right ow I have [Unit] Description=gunicorn daemon After=network.target [Service] User=usr Group=www-data WorkingDirectory=/home/usr/myproject ExecStart=/home/usr/myproject/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/rc/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target How do I add the second project that is for the subdomain.domain.com -
Django Gunicorn and sockets
I have a Django project, running on Gunicorn server. I also have a RPi computers connected to the same network, that do some other stuff. On a RPi I create a socket and wait for a connection. On a Django project, in a particular view, I open a socket and connect to the one on RPi. This works easily on a Django debug mode, with its default "runserver", but not on Gunicorn. As I try to open a socket, I sometimes get a Worker Timeout Error. Is there a better way to do something like this in particular (connecting Django with RPi for example)? Thank you for your help. -
django cursor.execute("UPDATE...another model ) while saving current model form
How can i update another model using cursor.execute("UPDATE..., while overriding a model save method. I have 2 models class Medication_List(models.Model): id = models.AutoField(primary_key=True) medication_name=models.CharField(max_length=250, blank=True, editable=True) medications_category = models.ForeignKey(Medication_Category,on_delete=models.CASCADE, blank=False, default=1) class Medications_Bridge(models.Model): id = models.AutoField(primary_key=True) order_details =models.ForeignKey(GeneralConsulting, on_delete=models.CASCADE) medication_name_id = models.ForeignKey(Medication_List, on_delete=models.CASCADE) def save(self, *args, **kwargs): quantity_sold = Medications_Bridge.objects.raw("SELECT *,..... ) ..... quantity_received = New_stock_purchases.objects.raw("SELECT *,.....) ...... current_stock = r.total_quantity_received - e.total_quantity_sold cursor.execute("UPDATE medication_productsapp_medication_list SET stock = %s WHERE id = %s" % (current_stock, self.medication_name_id.id)) transaction.set_dirty() transaction.commit() #i already tried transaction.commit_unless_managed() but it didn't work super(Medications_Bridge, self).save(*args, **kwargs) when i save a record,nothing happens to my cursor function. it does not update the other model's record. Is such a thing possible in django or am i missing something. I know i can use signals but i have a circular import problem which limits me from using signals. The @receiver decorator keeps giving me an error since Medications_Bridge(models.Model) already imports Medication_List(models.Model). Any help will be appreciated. -
django: Cannot assign "1": "TitleVideoModel.video_id" must be a "VideosModel" instance
i try to create api for add items in my database table, my curent code is : https://github.com/scaltro/youtubeapp/blob/master/myupload/views.py, problem is when i try to post data in my api : http://142.93.130.167:1080/api/titles return this error : Cannot assign "1": "TitleVideoModel.video_id" must be a "VideosModel" instance what is wrong ? how i can fix this error ? -
Running a django website without models.py and views.py
I did develop most of the front end but I am thinking to hire a freelance frontend developer(HTML, CSS and JS) to refine the design and make the site look professional. I am not yet comfortable to share my code with him. Is there any way in which he can run the django app without having models.py & views.py and work on html, css and js files. Any leads on this matter is appreciated. Thanks -
Parse URL w/ django & nginx
So I'm building a django web application and trying to deploy it with nginx. The langing page loads, but when I click on links, I get nginx 400 Bad Request errors. The url in the browser will look like: "GET /%7B$%%20url%20'members:member_login'%20%%7D HTTP/1.1" 400 173 "-" "-" "-" However, if I go into the browser and manually delete the extra characters to get: /url'members:member_login' Then it works and renders the page just fine. Does anyone know what I can put in my nginx config file or in the django code to address this issue? It's been stumping me for literally 2 weeks. -
APIView chaining in Django
I want to chain the call of API's, what I have is: from django.views import View from rest_framework.views import APIView from rest_framework.response import Response class ChildAPI(APIView) def get(self, request): store_id = request.GET.get('store_id) prodcuts = ProductsModel.objects\ .filter(store_id=store_id)\ .annotate(SUM('price'))... etc x = products['price__sum'] y = products['tax__sum'] Now rather then returning an response from the ChildAPI I rather would like to pass the x and y parameters via post to ParentAPI which will then return the response as: class ParentAPI(APIView): def post(self, request): store_id = request.POST.get('store_id') x = request.POST.get('x') y = request.POST.get('y') AwesomeModel.objects.filter(...).update(x=x,y=y) return Response({"code": 1, "message": "Updated"}) I was reading Calling a REST API from Django view, As the parameters aren't passed via post and url is hited via requests, can't I do it without domainname.com i.e. as we do via namespace from Django templates? Note: I have the ParentAPI url pattern in another Django App urls file, The way we can one function from another can I call one API from another passing parameters wrapped via post -
Django Google Sign in ModuleNotFoundError at /auth/complete/google-oauth2/
I am trying to create login with google in Django login so when I create my 'Login with Google' it goes to google login page but on selecting Google account it shows an error, ModuleNotFoundError at /auth/complete/google-oauth2/ No module named 'social' My project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('pages.urls')), path('accounts/', include('django.contrib.auth.urls')), path('auth/', include(('social_django.urls', 'social_django'), namespace='social')), path('admin/', admin.site.urls), ] settings.py import os INSTALLED_APPS = [ #..., 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'django', ] MIDDLEWARE = [ #... #... ] ROOT_URLCONF = 'trydjango.urls' TEMPLATES = [ { 'BACKEND': '# ...', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', # Google login 'social_django.context_processors.login_redirect', # Google Login ], }, }, ] DATABASES = { 'default': { # ... # ... } } AUTH_PASSWORD_VALIDATORS = [ # .... ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for Google authentication 'social_core.backends.google.GoogleOAuth', # 'social_core.backends.github.GithubOAuth2', # for Github authentication # 'social_core.backends.facebook.FacebookOAuth2', # for Facebook authentication 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.debug.debug', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details', 'social.pipeline.debug.debug', ) SOCIAL_AUTH_GOOGLE_OAUTH2_IGNORE_DEFAULT_SCOPE = True SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile' ] … -
How to generate bubble chart (Chart.js) using data from database FILTERED by user in Django?
I'm new to Django and stuck in one place that didn't seem to be such a problem. I'm trying to do dynamic bubble chart using Python, Django, MySQL and Chart.js. I have organizations stored in my database. They have some attributes like name, income, amount of recipients, etc.I'm showing it to user and he can filter it (for ex he can display organizations that only have more recipients than specified by user). Then I want to create a bubble chart that shows these organizations. I managed to do that, but using all database records (static solution, without user interaction). So, on my bubble chart now I can see everything and I would like to make it dynamic - dependant of user input (showing only organizations that are filtered). Filtered data are in filter.qs in myuserlist1.html file. Now I use the code below in my views.py to have all records from database in JSON format under defined URL: class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): organizations = Opp.objects.all().values() data = list(organizations) return Response(data) def search(request): user_list = User.objects.all() user_filter = UserFilter(request.GET, queryset=user_list) return render(request, 'user_list1.html', {'filter': user_filter})''' Url that I use for store results: url(r'^api/chart/data/$', ChartData.as_view()), … -
Django templates exclude field from form
I'm working with django-bootstrap4. I want to exclude one field from form. How can I do that with bootstrap4. my view: {% for item in form %} {% cycle 'row' '' as row silent %} {% if row %} <div class="row">{% endif %} <div class="col-md-6"> {% bootstrap_field item exclude=item.insured_type %} </div> {% if not row %} </div> {% endif %} {% endfor %} I read the documentation and bootstrap_field have exclude parameter but I have no idea how to use that. I wanted to exclude field that name insured_type. -
Django - URL not found using generic views
I am writing a basic Events app which contains of two modules(apps) so far : users and events. So far, I've been able to handle users, but on events, I can't use Update, Detail and Delete generic views. All of them return 404. My views.py: class EventListView(ListView): models = EventModel template_name = 'event_list.html' queryset = EventModel.objects.order_by('start_date_time') class EventUpdateView(UpdateView): models = EventModel fields = ['event_type','start_date_time' ] template_name = 'event_update.html' class EventDeleteView(DeleteView): models = EventModel template_name = 'event_delete.html' success_url = reverse_lazy('event_list') class EventDetailView(DetailView): models = EventModel template_name = 'event_detail.html' My urls.py (in project folder): urlpatterns = [ path('', include('pages.urls')), path('admin/', admin.site.urls), path('users/', include('users.urls')), path('users/', include('django.contrib.auth.urls')), path('events/', include('events.urls')), ] My urls.py (in events app): urlpatterns = [ path('', views.EventListView.as_view(), name='event_list'), path('<int:id>', views.EventDetailView.as_view(), name='event_detail'), path('<int:id>/edit/', views.EventUpdateView.as_view(), name='event_update'), path('<int:id>/delete/', views.EventDeleteView.as_view(), name='event_delete'), ] What am I doing wrong? I've been searching the whole day and still have no idea how this might be wrong. Note that the first line works (EventListView) but the other lines don't. By the way, I am using the book Django for Beginners. Most of the code here is identical to the code in the book. -
Django registration is not working
I am trying to add a user registration page but its showing NoReverseMatch at /register/ Here is my project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('pages.urls')), path('accounts/', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), ] Pages urls.py from django.urls import path from .views import * from django.contrib.auth import views app_name = 'pages' urlpatterns = [ path('', home_view, name='home'), path('register/', register_user, name='register'), ] Pages views.py def home_view(request, *args, **kwargs): return render(request, 'home.html', {}) def register_user(request, *args, **kwargs): if request.method=='POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) return redirect('home') else: form = UserCreationForm() context = {'form': form} return render(request, 'register.html', context) register.html <!DOCTYPE html> <html> <head> <title>Register</title> </head> <h2>Register here</h2> <body> <form method="post" action="{% url 'register' %}"> {% csrf_token %} {% if form.errors %} <p>Invalid details</p> {% endif %} {{ form }} <input type="submit" value="Register"> </form> </body> </html> All is fine but still it's showing error NoReverseMatch at /register/ Reverse for 'register' not found. 'register' is not a valid view function or pattern name. -
Django rest serialization - Passing JSON to Javascript
Disclaimer - Django noob, especially REST Framework. I'm trying to create an app that for this purposes passes JSON to the template. I figured Django Rest would be ideal. I have set up a user profile so the user can select various attributes (works fine), and now want to pass a JSON of all the user's selections to template. Think of it as a "my profile" page. View: profile = Profile.objects.filter(user=request.user) serializer = ProfileSerializer(profile, many=True) myteam = JsonResponse(serializer.data, safe=False) print(myteam.content) ## to see what's being passed Template: console.log({{myteam}}); Django server output: b'[{"user": "DAVE", "GK1": {"id": 1001, "ShortName": "J. Strummer", "Club": "CLUB", "Shirt": "SHIRT.png", "ShortClub": "ETC", "ShortPos": "FW", "CurrentVal": "10", "TotalPoints": 1}, "GK2": {"id": 320, "ShortName": "D. Jones", "Club": "CLUB2", "Shirt": "ETABE.png", "ShortClub": "ETABE", "ShortPos": "GK", "CurrentVal": "4.5", Template - Google Chrome JS console: Uncaught SyntaxError: Invalid or unexpected token Template - Chrome details: console.log(b&#39;[{&quot;user&quot;: &quot;mikey&quot;, &quot;GK1&quot;: {&quot;id&quot;: 1001, &quot;ShortName&quot;: &quot;J. Strummer&quot;, &quot;Club&quot;: &quot;ETC&quot;, &quot;Shirt&quot;: &quot;SHIRT.png&quot;, &quot;ShortClub&quot;: &quot;ETC&quot;, &quot;ShortPos&quot;: &quot;FW&quot;, &quot;CurrentVal&quot;: &quot;10.0&quot;, &quot;TotalPoints&quot;: 1}, // lot's more of this Noob Conclusion: I don't seem to be getting a "clean" JSON object passed to the template from the server. Possibly due to the b'[ .... is this bytes literal? Perhaps I should … -
if-statement doesn't work in for-loop
I have an issue with the if-statement and need some help. This is a short code-snippet in html: {% for category in categories %} {% if category == 'christmas' %} <p>{{category}} 1</p> {% else %} <p>{{category}} 2</p> {% endif %} {% endfor %} With the for-loop I walk through categories and check them with an if-statement for the string 'christmas'. The paragraph is always the second one, ending with a 2. Still, it appears that the category with the name 'christmas' comes up. That means, that in the if-statement "category" is different than in the p-tag. In fact, category is empty in the if-statement. Why? Can someone help here, please. Thanks! -
How to Get a Distinct Filtered QuerySet In Django Without Using the distinct Method?
Below is my post model. class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) content = models.TextField() datetime = models.DateTimeField(auto_now_add=True) votes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="post_votes", default=None, blank=True) tags = models.ManyToManyField(Tag, default=None, blank=True) I want to filter posts which contain a certain query in their title, content or as the name of one of their tags. To do this I've tried: query_set = Post.objects.filter(Q(content__icontains=query)| Q(tags__name__icontains=query)| Q(title__icontains=query)) But this often returns QuerySets with duplicate results. I have tried using the distinct method to solve this, but that results in incorrect ordering when I sort the posts later on by the number of votes they have: query_set.annotate(vote_count=Count('votes')).order_by('-vote_count', '-datetime') If anybody could help me I would be very grateful. Jack -
Django + Apache2 + Ubuntu + WSGI + sqlite3 - attempt to write a readonly database. How to fix?
I know there are tons of questions like this here, on SO, but absolutely nothing worked for me. As the title says, I am trying to configure my Django app using Apache2 and mod_wsgi. Unfortunately, when I try to log into the app: OperationalError at /3gjTaZ446V/admin/login/ attempt to write a readonly database Details: I'm logged in as root. My config looks like this: <VirtualHost *:80> ServerName test.domain.com DocumentRoot /var/www/3gjTaZ446V ErrorLog ${APACHE_LOG_DIR}/3gjTaZ446V_error.log CustomLog ${APACHE_LOG_DIR}/3gjTaZ446V_access.log combined Alias /static /var/www/3gjTaZ446V/mips_geonomie/static/ <Directory /var/www/3gjTaZ446V/mips_geonomie/static> Require all granted </Directory> <Directory /var/www/3gjTaZ446V/mips_geonomie/logs/> Require all granted </Directory> <Directory /var/www/3gjTaZ446V/mips_geonomie> <Files db.sqlite3> Require all granted </Files> </Directory> <Directory /var/www/3gjTaZ446V/mips_geonomie/config> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess 3gjTaZ446V python-home=/var/www/.virtualenvs/3gjTaZ446V python-path=/var/www/3gjTaZ446V/mips_geonomie WSGIProcessGroup 3gjTaZ446V WSGIScriptAlias / /var/www/3gjTaZ446V/mips_geonomie/config/wsgi.py </VirtualHost> The permissions on my project root: $ ls -altr total 184 drwxr-xr-x 3 root root 4096 Aug 19 09:44 .. drwxr-xr-x 2 root root 4096 Aug 19 09:44 requirements -rwxr-xr-x 1 root root 538 Aug 19 09:44 manage.py -rw-r--r-- 1 root root 200 Aug 19 09:45 .env drwxr-xr-x 4 root root 4096 Aug 19 09:45 config drwxr-xr-x 2 root www-data 4096 Aug 19 09:45 logs drwxr-xr-x 5 root root 4096 Aug 19 09:45 api drwxr-xr-x 6 root root 4096 Aug 19 09:45 static … -
django-admin not finding modules / apps not found
I have something like this: project |-- config | |-- settings | | |-- settings1.py | | |-- settings2.py | |-- wsgi.py |-- apps_f | |-- appName | | |-- apps.py | | |-- (otherstuff) |-- manage.py The problem is that when I run django-admin check --settings=config.settigs.settigs1 and with PYTHONPATH=$project I get: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. I have changed DJANGO_SETTINGS_MODULE environment var accordingly Interestingly, If I change the 'DJANGO_SETTINGS_MODULE' in manage.py and run it it works! Also, it may be relevant that If I try to add app1 to INSTALLED_APPS as 'apps_f.appName.apps.AppNameConfig' it complains that the name isn't correct: django.core.exceptions.ImproperlyConfigured: Cannot import 'appName'. Check that 'app_f.appName.apps.AppNameConfig.name' is correct. But it is correct. If I import it as 'app_f.appName' then it works but I don't know what's the difference? Please help, I'm stuck. -
django can't submit comment to database
I was trying to add a comment function to my django app, but whatever I did, the comment submitted just wouldn't show up in database, can't figure out why. Here're some codes I worked with, please have a look. the models.py part class Comment(models.Model): name = models.CharField(max_length=80) email = models.EmailField() text = models.TextField() post = models.ForeignKey(Post, related_name='comments') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) verbose_name="评论" verbose_name_plural="评论" def __str__(self): return 'Comment by {} on {}'.format(self.name, self.post) the forms.py part from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model=Comment fields=('name','email','text') the views.py part def post_comment(request,id): post=get_object_or_404(Post,id=id) if request.method=='POST': form=CommentForm(request.POST) if form.is_valid(): name=request.POST.get('name','') email=request.POST.get('email','') text=request.POST.get('text','') comment=Comment(name=name,email=email,text=text,post=14) comment.save() return redirect(post) else: form=CommentForm() comment_list = post.comments.all() context={ 'post':post, 'form':form, 'comment_list':comment_list } return render(request,'post_detail.html',context=context) return redirect(post) and the post_detail.html part <form action="" method="POST" class="mb-5">{% csrf_token %} <div class="form-group"> <label for="exampleInputPassword1">名称</label> <input name="name" type="name" class="form-control" id="exampleInputPassword1" placeholder="Name"> </div> <div class="form-group"> <label for="exampleInputEmail1">邮箱</label> <input name="email" type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">评论</label> <textarea name="text" class="form-control" id="exampleFormControlTextarea1" placeholder="Comment area..." rows="5"></textarea> </div> <button type="submit" class="btn btn-primary" value="post_comment">提交</button> </form> Any suggestions? Thanks. -
Why can't I move page by ajax?
My application makes screen transition by ajax.I wrote codes in one.html like <html> <head> <meta charset="UTF-8"> <title>Top</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="jquery.pjax.js"></script> </head> <script type="text/javascript"> $(function() { $.pjax({ area: '#main' }); $(document).bind('pjax:render', function() { $('#main').attr({ 'class': 'fadeInUp' }); }); }); </script> <body> <p> name </p> <input type="text" name="name" size="10"> <p class="button"><a href="{% url 'app:two' %}">Next</a></p> </body> </html> in two.html <p> age </p> <input type="text" size="10"> <p class="button"><a href="{% url 'app:three' %}">Next</a></p> in urls.py from django.urls import path from . import views from django.views.generic import TemplateView app_name = 'app' urlpatterns = [ path('', views.top, name='top'), path('one/', TemplateView.as_view(template_name='one.html'), name='one'), path('two/', TemplateView.as_view(template_name='two.html'), name='two'), path('three/', TemplateView.as_view(template_name='three.html'), ] When I click Next button in one.html of <p class="button"><a href="{% url 'app:two' %}">Next</a></p>,url is changed into http://127.0.0.1:8000/app/two/ .But I want to change page by ajax.Why can't I do it?How should I fix this? -
Django JSONDecodeError at ...= get_response(request)
When i run the server and look at localhost i got this error: JSONDecodeError at ...Traceback response = get_response(request) What am i doing wrong? My Code is : from django.shortcuts import render import json import requests def home(request): response = requests.get('https://api.ipify.org') data = response.json() dump = json.dumps(data) return render(request, 'catalog/home.html', {'ip': dump} ) -
django RetrieveAPIView not working
i try to view item in django with RetrieveAPIView ... here is source code of my complete application : https://github.com/scaltro/youtubeapp/blob/master/myupload/urls.py when i try to view one single element api return 404 not found. example : http://142.93.130.167:1080/api/videos/1 where i wrong ? -
Ordered ManyToMany relation in Django with custom Field
In Django, I would like to have an ordered many-to-many-relation. Assume I have, say, the models OrderedList and Item, and I want to be able to insert Item()s into an OrderedList() at a specific index, I want to be able to retrieve the Item()s of an OrderedList() in their order and also to change the order of Item()s on an OrderedList I already found Define an order for ManyToManyField with django and https://github.com/gregmuellegger/django-sortedm2m Both the github repo and the accepted answer in the SO question are working with the same architecture: They create an additional integer field, say order_index, on the junction ("Through") table which represents the position of the Item() on the OrderedList(). Honestly, I do not like that too much. If I see this correctly, having the order stored on the junction table can create inefficiency when I want to reorder Item()s: Imagine, I want to change the position of an Item() on an OrderedList() which has n Item()s. This means O(n) database updates to reorganize the order indices. I would like to avoid this. I think of an architecture where I have an ordinary many-to-many-relation and one additional column on the OrderedList table which holds a list …