Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AWS S3 has to load before I execute anything on the command line
I have a django project integrated with s3, and everytime I want to execute something on the command line, e.g. python manage.py migrate, the terminal has to load this first: BEGIN REQUEST++++++++++++++++++++++++++++++++++++ Request URL = https://ec2.amazonaws.com?Action=DescribeRegions&Version=2013-10-15 RESPONSE++++++++++++++++++++++++++++++++++++ Response code: 200 <?xml version="1.0" encoding="UTF-8"?> <DescribeRegionsResponse xmlns="http://ec2.amazonaws.com/doc/2013-10-15/"> <requestId>936a670c-3q31-33kc-8713-1d0gbe6ad222</requestId> <regionInfo> <item> <regionName>ap-south-1</regionName> <regionEndpoint>ec2.ap-south-1.amazonaws.com</regionEndpoint> </item> <item> <regionName>eu-west-3</regionName> <regionEndpoint>ec2.eu-west-3.amazonaws.com</regionEndpoint> </item> <item> <regionName>eu-west-2</regionName> <regionEndpoint>ec2.eu-west-2.amazonaws.com</regionEndpoint> </item> <item> <regionName>eu-west-1</regionName> <regionEndpoint>ec2.eu-west-1.amazonaws.com</regionEndpoint> </item> <item> <regionName>ap-northeast-2</regionName> <regionEndpoint>ec2.ap-northeast-2.amazonaws.com</regionEndpoint> </item> <item> <regionName>ap-northeast-1</regionName> <regionEndpoint>ec2.ap-northeast-1.amazonaws.com</regionEndpoint> </item> <item> <regionName>sa-east-1</regionName> <regionEndpoint>ec2.sa-east-1.amazonaws.com</regionEndpoint> </item> <item> <regionName>ca-central-1</regionName> <regionEndpoint>ec2.ca-central-1.amazonaws.com</regionEndpoint> </item> <item> <regionName>ap-southeast-1</regionName> <regionEndpoint>ec2.ap-southeast-1.amazonaws.com</regionEndpoint> </item> <item> <regionName>ap-southeast-2</regionName> <regionEndpoint>ec2.ap-southeast-2.amazonaws.com</regionEndpoint> </item> <item> <regionName>eu-central-1</regionName> <regionEndpoint>ec2.eu-central-1.amazonaws.com</regionEndpoint> </item> <item> <regionName>us-east-1</regionName> <regionEndpoint>ec2.us-east-1.amazonaws.com</regionEndpoint> </item> <item> <regionName>us-east-2</regionName> <regionEndpoint>ec2.us-east-2.amazonaws.com</regionEndpoint> </item> <item> <regionName>us-west-1</regionName> <regionEndpoint>ec2.us-west-1.amazonaws.com</regionEndpoint> </item> <item> <regionName>us-west-2</regionName> <regionEndpoint>ec2.us-west-2.amazonaws.com</regionEndpoint> </item> </regionInfo> </DescribeRegionsResponse> and this creates a few seconds delay for my command to execute. Is there any way I can prevent this from happening as it's causing delays in development. -
NoReverseMatch at /polls/top/ 'polls' is not a registered namespace
Parent app name is mysite,child app name is polls. I wrote in views.py from django.shortcuts import render from .models import Polls def top(request): data = Polls.objects.order_by('-created_at') return render(request,'index.html',{'data':data}) def detail(request): data = Polls.objects.order_by('-created_at') return render(request,'detail.html',{'data':data}) in child app's urls.py from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns=[ url('top/', views.top, name='top'), url('detail/<int:pk>/', views.top,name='detail'), ] in parent app's urls.py from django.contrib import admin from django.conf.urls import url,include app_name = 'polls' urlpatterns = [ url('admin/', admin.site.urls), url('polls/', include('polls.urls')), ] in index.html <main> {% for item in data %} <h2>{{ item.title }}</h2> <a href="{% url 'polls:detail' item.pk %}">SHOW DETAIL </a> {% endfor %} </main> When I access top method, NoReverseMatch at /polls/top/ 'polls' is not a registered namespace error happens.I am using Django 2.0,so I think namespace cannot used.I wrote app_name ,so I really cannot understand why this error happens.How should I fix this?What is wrong in my code? -
Outdated Pipfile.lock
I'm trying to deploy a large django project to heroku. I installed Heroku CLI, logged in, created an app and ran: git push heroku master I have a Pipfile and requirements.txt already set up. I added a runtime.txt to specify that I need python 2.7. This is also in the Pipfile. This is what I get from pushing to heroku: Counting objects: 12159, done. Delta compression using up to 2 threads. Compressing objects: 100% (4853/4853), done. Writing objects: 100% (12159/12159), 20.94 MiB | 1.82 MiB/s, done. Total 12159 (delta 6859), reused 12036 (delta 6751) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.4 remote: -----> Installing pip remote: -----> Installing dependencies with Pipenv 11.8.2… remote: Your Pipfile.lock (3b2ba9) is out of date. Expected: (83a5b4). remote: Aborting deploy. remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy.... remote: remote: ! Push rejected to camp-infinity. remote: To https://git.heroku.com/camp-infinity.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/camp-infinity.git' I'm not sure why it tries to install python 3, and it also doesn't like my Pipfile.lock file. I've tried … -
Try to use ajax loading data from mysql with django rest framework
I try to load ajax from mysql with datatable and django rest framework. But I got some errors. serializers.py from rest_framework import serializers from nba.models import News class NewsSerializer(serializers.ModelSerializer): class Meta: model = News fields = '__all__' views.py from nba.models import News from nba.serializers import NewsSerializer # Create your views here. from rest_framework import viewsets, status from rest_framework.response import Response from django.template.response import TemplateResponse from django.http.response import HttpResponse from nba.models import query_nba_by_args def index(request): html = TemplateResponse(request, 'index.html') return HttpResponse(html.render()) # Create your views here. class NewsViewSet(viewsets.ModelViewSet): queryset = News.objects.all() serializer_class = NewsSerializer def list(self, request, **kwargs): try: nba = query_nba_by_args(**request.query_params) serializer = NewsSerializer(nba['items'], many=True) result = dict() result['data'] = serializer.data result['draw'] = nba['draw'] result['recordsTotal'] = nba['total'] result['recordsFiltered'] = nba['count'] return Response(result, status=status.HTTP_200_OK, template_name=None, content_type=None) except Exception as e: return Response(e, status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None) There is my reference code. https://github.com/twtrubiks/DRF-dataTable-Example-server-side And when i vistied http://127.0.0.1:8000/index/ DataTables warning: table id=datatables - Ajax error. http://127.0.0.1:8000/api/news/ will get Object of type 'TypeError' is not JSON serializable How to deal with this error.plz give me some advice or some file i ineed to provide thanks alot -
How To add Models with OneToOneField to every of some ForeignKey Custom User Models
The following scenario: I need a Custom User Model with ForeignKey to the user model. e.g.: a User can have some Planets class UserPlanet(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(default='planet', max_length=40) For each created planet, there are other models that have a OneToOneField. e.g. a Model which contains size, color or its favorite animal, however: class PlanetValues(models.Model): user_planet = models.OneToOneField(UserPlanet, related_name='planet_values', on_delete=models.CASCADE) size = models.IntegerField(default=1000) What is the best way for a Django View to choose one of the Planet and the Informations on a template was filtered to the corresponding planet. This is a simple example, but the principle does not change. How can I handle this case? -
Manipulate dictionaries from values() output
Iam trying to use the ForeingKeys ids to search in others tables, to get the ids iam using : infos = LOGIN.objects.filter(servicesName="example").values('user_id','passwd_id') This returns to me the follow : So where is my question, how can i get the value '3' from 'passwd_id' ? Or even better is there a easiest way to do it ? Sorry about my english -
After deleting my database I'm still getting "ProgrammingError: column post_post.hash does not exist"
How is this possible? I did python manage.py flush which deleted the database. I also uninstalled and re-installed django. I then did makemigrations and migrate. But I'm getting this error in my log.django file: File "/home/zorgan/app/env/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/zorgan/app/env/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/zorgan/app/env/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column post_post.hash does not exist LINE 1: SELECT "post_post"."id", "post_post"."hash", "post_post"."us... It's referring to my models here: class Post(models.Model): hash = models.CharField(max_length=18, default=random_string, null=True, blank=True) class PostScore(models.Model): user = models.ForeignKey(User, blank=True, null=True) post = models.ForeignKey(Post, related_name='score') Any idea what's going on? -
Editing without registration in Django
I am creating a web application where users can book seats for an event. However, no registration will be needed. The reason is that I want to avoid the registration process for the users because it's more user-friendly and the second (and more important) point is that the visitors of my web page will book for an event probably only once a year. So it just does not make sense to create an account. But the people should be able to edit their booking. My idea is the following: If someone wants to book seats for the event, they have to provide an email address. After successful form submit, I will send them an email containing a link to the edit form of the booking. That should work with an UUID that is not public. I mean that every booking contains - beside the public key - an UUID (which is not public). I will send UUID only to the creator what enabled him to edit the booking. For example: You can edit your booking at example.com/booking/(UUID)/edit in the email. It's not really a question, but I am relatively unexperienced with Django and just want to hear an opinion about … -
Why M I facing KeyError in my registration django?
I am having the following models.py: class UserProfile(models.Model): GENDER_CHOICES = ( ('m', 'Male'), ('f', 'Female'), ) USER_TYPE = ( ('s', 'Entrepreneur'), ('c', 'Mentor'), ('d', 'Investor'), ('v', 'Job Seeker'), ) user = models.OneToOneField(User, on_delete = models.CASCADE) birth_date = models.DateField(null=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) address = models.CharField(max_length=150) locality = models.CharField(max_length=30) state = models.CharField(max_length=30, default='Enter State') postal_code_4 = models.PositiveIntegerField(null=True) user_type = models.CharField(max_length=1, choices=USER_TYPE) skill_sets = models.CharField(max_length=150, default= 'Example:Computer Literacy/Information Technology/Business Experties') is_verified = models.BooleanField(default=False) def __str__(self): return self.user def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) And my views.py look something like this: def Registration(request): if request.user.is_authenticated: return HttpResponseRedirect('/profile/') if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user(username = form.cleaned_data['username'],email = form.cleaned_data['email'] , password = form.cleaned_data['password']) user.save() user_profile= UserProfile(user=user, address = form.cleaned_data['address']) user_profile.save() return HttpResponseRedirect('/profile/') else: return render(request, 'visit/registration/register.html', {'form': form},) else: form= UserRegistrationForm() context = {'form': form} return render(request, 'visit/registration/register.html', context ) I am sure I have made some error which I cant find in the above code since I am new to Django. I am trying to add a profile form after registration and facing the following error: KeyError at /register/ 'address' Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 2.0.2 Exception Type: KeyError Exception Value: … -
Django-signal / Sqlite-trigger when the user is deleted (edit user id who left a comment)
Help with the comments. The site has comments. Accordingly, the user table is used from the standard Auth + there is a table "Comments" in SQLite: class Comments(models.Model): UserID = models.ForeignKey(User, on_delete=models.CASCADE, default=0) CommentsText = models.TextField("Комментарий") LibraryID = models.ForeignKey(Library, on_delete=models.CASCADE, default=0) # Ссылка на библиотеку AddDate = models.DateTimeField(auto_now=True) def __str__(self): return self.CommentsText Suppose a person left a few comments, and then I want to delete his profile through the admin panel. It is necessary to make sure that his comments are not erased with him, but go to a specially created user with the name "Deleted_user" and conditional id = 999. I think I need to look to the side of pre_delete. But I do not have enough examples of this method. -
Issue with getting author when posting (Django)
Sorry to bother you all but I'm having an issue I have absolutely no understanding of. This is going to be fairly long so if you don't have a large amount of time on your hands please don't hesitate to ignore this question. My issue is with a tutorial for Django. I've already completed it once, so I've been trying to put a spin on it before learning more and completely rewriting it myself. I've removed a non-essential but good for organization app from the project called pages, as well as styling the actual templates. Nothing complicated, and nothing to do with the underlying way any of their code works. Time for where the actual question comes in, however first, here is the link to: The tutorial I'm following: http://intermediatedjango.com/ I was planning to link to more, but nothing but that is really relevant. In following this tutorial I've gotten to a section where you replace a part of the code you've written in the views.py file of the posts app. That section is replacing: class PostCreateView(CreateView): model = models.Post template_name = 'post_new.html' fields = ['message', 'author'] With the following: https://pastebin.com/UE5cvaQ4 After doing this and going to the page to … -
Django order search results by usage in foreign key relation
I would like to have my search results sorted by use in a foreign key relation when searching for one of my Django models. Example: Model "Tag" -> Many to Many <- Model "Post" If I am searching for a tag, I would like to get the query matching tags returned in the order they are used in the relation. This means the most used tag that meets the search criteria first, etc. Is that possible, if so, how? -
"Specified key was too long" error when migrating from sqlite to mysql on pythonanywhere
I am migrating my django webapp from sqlite to mysql on the pythonanywhere platform and I keep getting the following error: django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes') I tried several things including the answer here but couldn't make it work. Any suggestions? -
Django Block Heritage
I am trying to modify the part {% block contentLeft%} ... However, I can not change this part only. When I use {{super}} I get the full block but I can not change it ... I can not edit a block in a block. I used includes, I tried to remove the block tags for the body however I can not modify the tag contentLeft, contentCenter, contentRight I am also looking to change the name of modules in the administration page, do you have an idea? I changed the name of the models but I can not change the name of the "application" {% extends "base.html" %} {% block title %}Ma page Date{% endblock %} {% block body %} {{ block.super }} {% block contentLeft %} essai {% endblock %} {% block contentCenter %} centre {% endblock %} {% block contentRight %} droite {% endblock %} {% endblock %} {% load static %} {% block body %} <body> {% block header %} {% include 'header.html' %} {% endblock %} <div class="container-fluid"> <div class="row"> <div class="col-md-2"> {% block contentLeft %} Toto1 {% endblock %} </div> <div class="col-md-8"> {% block contentCenter %} Toto2 {% endblock %} </div> <div class="col-md-2"> {% block contentRight … -
Is it save to retrieve data from HTML attributes and send it to server through AJAX?
In my web application, I use a lot of requests with Ajax. I retrieve information via Html attributes and send them to the server. <div id="wrapper-posts"> {% for post in all_posts %} <!-- html code here --> <button class="delete-post" data-id="{{post.id}}" type="button">Delete post</button> {% endfor %} </div> <script type="text/javascript"> $(document).on("click",".delete-post",function(){ var id = $(this).data("id"); $(this).attr("disabled",true); $.ajax({ url:"", type:"post", data:{ csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), id:id, }, success:function(data){ $("#wrapper-posts").html($("#wrapper-posts",data)); } }); }); </script> I realize that user can easily modify the attributes with Inspect Element, and delete other post. What is the safe way to do it, or should I proceed with more parameters and not just the ID? like a data-code={{post.code}} where code is a random code, a length more than 10 chars. <button class="delete-post" data-id="{{post.id}}" data-code="{{post.code}}" type="button">Delete post</button> I really need helps to achieve that the safer way. Thank you! -
Django shuup migrate error
Getting error TypeError: startswith first arg must be bytes or a tuple of bytes, not str when try to python -m shuup_workbench migrate There is no answer anywhere File "PycharmProjects/untitled1/venv2/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 260, in create_model self.quote_name(field.column), File "PycharmProjects/untitled1/venv2/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 113, in quote_name return self.connection.ops.quote_name(name) File "PycharmProjects/untitled1/venv2/lib/python3.6/site-packages/django/db/backends/sqlite3/operations.py", line 153, in quote_name if name.startswith('"') and name.endswith('"'): -
Django GCBV UpdateView AttributeError - type object 'QuerySet' has no attribute '_meta'
I am stuck at this Point. I want a view that extends the User model with a ForeignKey named UserPlanet(models.Model) and some other views, that extends the UserPlanet Model by OneToOneField. My setup looks like listed below. If I try to reach the view by the url I get an AttributeError at /game/ type object 'QuerySet' has no attribute '_meta' How do I solve this? Unfortunately I am missing an approach. Unfortunately, I can not find anything in the django documentation views.py: from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from .models import UserPlanet, UserShips, UserDefense, UserBuildings class IndexView(LoginRequiredMixin, generic.UpdateView): context_object_name = 'planets' template_name = 'game/home.html' fields = ('name', 'planet_size', 'free_fields', 'max_temperature', 'min_temperature', 'planet_galaxy', 'planet_system', 'planet_position') def get_object(self, queryset=None): return self.request.user.userplanet_set.all() models.py: from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver class UserPlanet(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(default='Heimatplanet', max_length=40) planet_size = models.PositiveSmallIntegerField(default=150) free_fields = models.PositiveSmallIntegerField(default=150) max_temperature = models.SmallIntegerField(default=80) min_temperature = models.SmallIntegerField(default=-20) planet_galaxy = models.PositiveSmallIntegerField(default=1) planet_system = models.PositiveSmallIntegerField(default=1) planet_position = models.PositiveSmallIntegerField(default=1) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_user_planet(sender, instance, created, **kwargs): if created: UserPlanet.objects.create(user=instance) class UserResources(models.Model): user_planet = models.OneToOneField(UserPlanet, related_name='user_resources', on_delete=models.CASCADE) minerals = models.IntegerField(default=1000) # Mineralien food = models.IntegerField(default=0) # Nahrung energy = models.IntegerField(default=0) # … -
Passing a parameter through URL via loop
So, I'm trying to pass the name of the PDF to the URL so that the view can display the relevant PDF. urls.py path('show-invoice/<str:invoice>', views.pdf_view, name ="pdfview") views.py def pdf_view(request, invoice): invoicename = Laptop.objects.get(invoice=invoice) invoicename = invoicename.invoice pdfpath = settings.MEDIA_ROOT + invoicename pdfpath = pdfpath.replace('/', '\\') try: return FileResponse(open(pdfpath, 'rb'), content_type='application/pdf') except FileNotFoundError: raise Http404() models.py invoice = models.FileField(default='default.pdf', upload_to='uploads/') invoice_list.html <h2>View invoices</h2> {%for i in invoices%} <ul> <li> <a href = "{%url 'laptops:pdfview' invoice=i.invoice%}"> {{i.invoice}} </a> </li> </ul> {%endfor%} Now, my question is: Why does it work when I use invoice='default.pdf' and not when I useinvoice=i.invoice? I get the following error NoReverseMatch at /invoices/ Reverse for 'pdfview' with keyword arguments '{'invoice': 'uploads/default1.pdf'}' not found. 1 pattern(s) tried: ['show\\-invoice\\/(?P<invoice>[^/]+)$'] -
Unable to render PIL object base64 image on template
I'm trying to display a PIL object after converting to base64. I'm getting the base64 value in the src tag but the response is not rendered even after decoding import base64 import io def newrules(request): pic = con(select.fname) print(pic) buffered = io.BytesIO() pic.save(buffered, "PNG") img_str = base64.b64encode(buffered.getvalue()) template_code = """ {% load static %} <!DOCTYPE HTML> <html> <body> {% block pagecontent %} <div> <img src="data:image/png;base64,{{ img_str }}"> </div> <div> {{ img_str }} </div> </body> {% endblock %} </html> """ template = engines['django'].from_string(template_code) return HttpResponse(template.render(context={'img_str': img_str})) HTML souce code terminal API call responses Template rendered Any help will be highly appreciated. -
Sort objects in Django admin by a model @property?
I have two models - a Task model, and a Worker model. I have a property on Worker that counts how many tasks they have completed this month. class Task(models.Model): # ... completed_on = models.DateField() class Worker(models.Model): # ... @property def completed_this_month(self): year = datetime.date.today().year month = datetime.date.today().month return Task.objects.filter(worker=self, completed_on__year=year, completed_on__month=month).count() I've added this field to the Worker admin, and it displays correctly. I would like to be able to sort by this field. Is there a way to do this? -
Facebook login: Warning Insecure Login Blocked (with https on)
I'm trying to allow users to log in using Facebook. We have secured website (https) so I don't understand where could be the problem. When user clicks on "login via facebook" they get this error: Insecure Login Blocked: You can't get an access token or log in to this app from an insecure page. Try re-loading the page as https:// We use django-allauth and have set everything includin secret and app id. I don't know if this can help but I noticed that the url seems like this: https://www.facebook.com/v2.5/dialog/oauth?scope=email&state=1yohNoe0z0cV&redirect_uri=http%3A%2F%2F<OURSITE>.com%2Fen%2Faccounts%2Ffacebook%2Flogin%2Fcallback%2F&response_type=code&client_id=2056007991303623 There is this query param: redirect_uri=http%3A%2F%2F<OURSITE>.com It seems that there is s missing after http but it is just redirect. Do you know where is the problem? -
Django Migration Error
After importing Psycopg2==2.7.4 into my server, I can no longer run my server properly. After adding new fields, this is what happens now in my terminal whenever I try to make migrate after makemigrations(python manage.py migrate): Apply all migrations: admin, auth, buddysapp, contenttypes, oauth2_provider, sessions, social_django Running migrations: Applying buddysapp.0038_auto_20180321_0025...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 202, in handle targets, plan, fake=fake, fake_initial=fake_initial File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/migrations/executor.py", line 97, in migrate state = self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/migrations/executor.py", line 132, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/migrations/executor.py", line 237, in apply_migration state = migration.apply(state, schema_editor) File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 84, in database_forwards field, File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 231, in add_field self._remake_table(model, create_fields=[field]) File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 113, in _remake_table self.effective_default(field) File "/Users/hsi/Desktop/myvirtualenv/buddys/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 68, in quote_value raise ValueError("Cannot quote parameter value %r of type %s" % (value, type(value))) ValueError: Cannot quote parameter value <psycopg2._json.Json object at 0x10ea5e748> of type <class 'psycopg2._json.Json'> … -
Django slug two in one confusion
I'm trying to display a blog as follows: domain.com/blog/categoryA domain.com/blog/categoryA/post-one At the moment (1) works successfully, and (2) works partially, so it displays like: domain.com/post-one How can I set post category - posts that belong to that category. My urls.py: url(r'^(?P<slug>[-\w]+)/$', views.post_detail, name='post_detail'), url(r'^category/(?P<category_slug>[-\w]+)/$', views.list_of_post_by_category, name='list_of_post_by_category'), My views.py def list_of_post_by_category(request,category_slug): categories = Category.objects.all() post = Post.objects.filter(status='published') if category_slug: category = get_object_or_404(Category, slug=category_slug) post = post.filter(category=category) template = 'blog/category/list_of_post_by_category.html' context = {'categories': categories, 'post': post} return render(request, template, context) def list_of_post(request): post = Post.objects.filter(status="published") template = 'blog/post/list_of_post.html' context = {'post': post} return render(request, template, context) def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) template = 'blog/post/post_detail.html' context = {'post': post} return render(request, template, context) -
Django 1.11 Forbidden (403) CSRF verification failed. Request aborted
I am writing a login page with Django 1.11. When I want to enter the account name and password on the page this is what I received: Forbidden (403) CSRF verification failed. Request aborted. Here is my code: from django.shortcuts import render_to_response from django.http import HttpResponse from django.contrib import auth from django.template import RequestContext def login(request): if request.user.is_authenticated(): return HttpResponseRedirect('/index/') username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: auth.login(request, user) return HttpResponseRedirect('/index/') else: return render_to_response('login.html', context=locals()) And here is my template: <!doctype html> <body> <form action="" method="post"> <label for="username">用戶名稱:</label>{% csrf_token %} <input type="text" name="username" value="{{username}}" id="username"><br /> <label for="password">用戶密碼:</label> <input type="password" name="password" value="" id="password"><br /> <input type="submit" value="登入" /> </form> </body> -
Django template Tag not showing
I am confused about how Django template tag can be shown. I am using Django 2.0.3 and jQuery 3.3.1 I have this on a template called home.html: //home.html <script> $(".game-menu").click(function () { $(".game-menu").removeClass("active"); $(this).addClass("active") }); $("#buildings").click(function () { $("#main-content").load("{% url 'game:buildings' %}"); }); $("#overview").click(function () { $("#main-content").load("{% url 'game:overview' %}"); }); </script> <nav class="sidebar"> <ul class="nav nav-pills flex-column"> <li class="btn game-menu active" id="overview"> <a class="nav-link text-white">Übersicht</a> </li> <li class="btn game-menu" id="buildings"> <a class="nav-link text-white">Gebäude</a> </li> </ul> </nav> <!-- Page Content Holder --> <main class="text-white" id="main-content"> {% include 'game/overview.html' %} </main> including overview.html works fine as expected ( the template tag {{ planet.name }} showing on the page: //overview.html {% load static %} <div class="card"> <h2 class="card-header bg-dark">Übersicht - {{ planet.name }}</h2> <div class="card-body"> <h5 class="card-title">Special title treatment</h5> <p class="card-text">With supporting text below as a natural lead-in to additional content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> now the part that confuses me if I click on the nav button overview to load the overview.html via jQuery into <main id=main-content></main> the template was shown, but the template tag {{ planet.name }} will not be shown.