Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, How to get user sign up statistics?
I have a Django project that is using allauth to handle user logins and signups. All I am trying to do is have a way to view the sign-up stats. It would be nice to see how many user sign-ups there were today vs yesterday and so forth. I do not need any fancy graphs or reports, just numbers. I have done quite a lot of research on this and haven't seen a clean cut solution. Does anybody have a solution for this? Thanks, -
Django Getting this error with UpdateView
I have an update view for users to update their profiles. However I keep getting this error: NoReverseMatch at /user/2/edit Reverse for 'user_profile' with no arguments not found. 1 pattern(s) tried: ['user/(?P<pk>\\d+)/$'] Nothing I've tried is working (adding a pk, etc.). The UpdateView: class UserEditProfileView(LoginRequiredMixin,UpdateView): login_url = '/login/' model = UserProfile fields = [ 'first_name', 'profile_pic', 'location', 'title', 'user_type', 'website', 'about', 'twitter', 'dribbble', 'github' ] template_name_suffix = '_edit_form' success_url = reverse_lazy('users:user_profile') App urls: from django.conf.urls import url from users import views app_name = 'users' urlpatterns = [ url(r'^$',views.UserListView.as_view(),name='user_list'), url(r'^(?P<pk>\d+)/$',views.detailprofile,name='user_profile'), url(r'^(?P<pk>\d+)/edit$',views.UserEditProfileView.as_view(),name='user_profile_edit'), url(r'^login/$',views.user_login,name='user_login'), url(r'^logout/$',views.user_logout,name='user_logout'), url(r'^register/$',views.register,name='register'), ] Edit profile template: {% extends "users/base.html" %} {% block content %} <div class="form-base"> <h2>Edit Profile</h2> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> </div> {% endblock %} Let me know if you need to see anything else. -
URL redirection issue using PK
Hi guys I have a primary key issue with the following error : django.urls.exceptions.NoReverseMatch: Reverse for 'addteam' not found. 'addteam' is not a valid view function or pattern name. My app is simple : a user create a project then arrive to a page in a detail page with a button in order to invite user using mails ... the thing is I get the error just after creating the project Here is my code : urls.py: from django.conf.urls import url from website import views app_name = 'website' urlpatterns = [ url(r'^candidateIndex/$', views.CandidateIndex.as_view(), name='candidate_index'), url(r'^HRcreate/$', views.ProjectCreate.as_view(), name='HR_create'), url(r'^project/(?P<pk>[0-9]+)/$',views.ProjectDetailView.as_view(), name='ProjectDetails'), url(r'^project/(?P<pk>[0-9]+)/invite/$',views.create_invite, name='addteam'), ] views.py: from django.shortcuts import render from django.views import generic from django.views.generic import TemplateView from django.views.generic.edit import CreateView, UpdateView, DeleteView from .forms import InviteForm from invitations.models import Invitation from .models import project from django.core.urlresolvers import reverse # Create your views here. class HomePage(TemplateView): template_name= 'index.html' class CandidateIndex(TemplateView): template_name= 'candidateIndex.html' class HRIndex(TemplateView): template_name= 'HRindex.html' class ProjectDetailView(generic.DetailView): model = project template_name = 'project_details.html' class ProjectCreate(CreateView): model = project fields = ['project_name'] template_name = 'project_form.html' def create_invite(request, pk): if request.method == "POST": invite_form = InviteForm(data=request.POST) if invite_form.is_valid(): email1 = invite_form.cleaned_data['email1'] email2 = invite_form.cleaned_data['email2'] email3 = invite_form.cleaned_data['email3'] email4 = invite_form.cleaned_data['email4'] email5 = invite_form.cleaned_data['email5'] … -
Django redirect_authenticated_user: True not working
I'm writing an application in Django 1.11. myapp/urls.py pattern looks like from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth.views import LoginView urlpatterns = [ url(r'^login/$', LoginView.as_view(), {'redirect_authenticated_user': True}), url('^', include('django.contrib.auth.urls')), url('^', include('pages.urls')), url(r'^pages/', include('pages.urls')), url(r'^search/', include('search.urls')), url(r'^admin/', admin.site.urls), ] I want logged in user to be redirected when trying to access /login page. For that I have set redirect_authenticated_user to True as per given in documentation here But, when I access /login after successfull login, it does not redirect -
Django allauth, multiple form signup
I'm trying to create a multi form signup with django allauth. (I originally tried django wizard, but opted out of that as sign up isn't necessarily a linear path, depending on earlier form data filled out by the user). What's the best way to get django allauth to work with multi page signup? I thought that using a series of form views with the first creating the user and login them in: @require_http_methods(['GET', 'HEAD', 'POST']) def profile_view(request, price_id): form = ProfileForm() if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): form.save() user = authenticate(request, username=form.cleaned_data['email'], password=form.cleaned_data['password1']) login(request, user) return redirect('users:supply_address') return render(request, 'pages/signup.html', {'form': form}) followed by a series of similar views which require login and then ending with a view that uses the complete_signup method from django-allauth. @login_required @require_http_methods(['GET', 'HEAD', 'POST']) def direct_debit_view(request): form = DirectDebitForm() if request.method == 'POST': form = DirectDebitForm(data=request.POST) if form.is_valid(): request.session.update(form.cleaned_data) complete_signup(request, user, settings.ACCOUNT_EMAIL_VERIFICATION,settings.LOGIN_REDIRECT_URL) return redirect(settings.LOGIN_REDIRECT_URL) return render(request, 'pages/signup_postcode.html', {'form': form}) And overridding the url used for login for django-allauth to point to the first signup view. However I'm not sure if this is the best approach? url(r'^account/signup/$', views.profile_view, name='profile'), -
How to register a visitor (guest), after submitting an order form, and immediately authorize his on site with this data?
There is Django 1.11.5 with an override user model (client). Authorization occurs by email + password, some fields are removed in the admin panel, but otherwise - the standard model of the user from Django (I use AbstractUser). Also, there is an application (order_form) with many fields that can be filled in by both guests and authorized site visitors. How to make sure that when you send this form, if the visitor is GUEST (unauthorized) and he does not have an account on the site (check by email), he automatically registered (with the email that he indicated in the form and randomly generated password + sending a letter with this data to the mail)? Also, I would like to immediately redirect to his personal cabinet and authorize this user, using his email and that generated password. I will be glad to any help. -
url for accounts/profile in Django
I'm using Django 1.11 and new to it. I'm using default login and logout functions. When I login, it redirects to accounts/profile and then generates error as Using the URLconf defined in myapp.urls, Django tried these URL patterns, in this order: ^ ^login/$ [name='login'] ^ ^logout/$ [name='logout'] ^ ^password_change/$ [name='password_change'] ^ ^password_change/done/$ [name='password_change_done'] ^ ^password_reset/$ [name='password_reset'] ^ ^password_reset/done/$ [name='password_reset_done'] ^ ^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$ [name='password_reset_confirm'] ^ ^reset/done/$ [name='password_reset_complete'] ^ ^$ [name='home'] ^pages/ ^search/ ^admin/ The current path, accounts/profile/, didn't match any of these. Is accounts built-in function in Django? If it is, how to access url to accounts app? If no, why it is there? -
can someone explain meaning of `# __unicode__ on Python 2` in Django documentation
# __unicode__ on Python 2 Django newbie here, I have tried to search for the meaning of this comment above but couldn't find information about it. In the Django documentation I find this comment in many parts of the code , does that mean that this section is only if I use Django with Python 2 or it means something else ? I mean functions like this def __str__(self): # __unicode__ on Python 2 return "%s the place" % self.name In this Example code: from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __str__(self): # __unicode__ on Python 2 return "%s the place" % self.name class Restaurant(models.Model): place = models.OneToOneField( Place, on_delete=models.CASCADE, primary_key=True, ) serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) def __str__(self): # __unicode__ on Python 2 return "%s the restaurant" % self.place.name class Waiter(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): # __unicode__ on Python 2 return "%s the waiter at %s" % (self.name, self.restaurant) -
Django: Automatically setting a calculated form field value
One of my HTML forms is concerned with creating a purchase to add to my database. The user selects items from a ManyToManyField. These items, within the database, have their own prices. There is a price box at the bottom of the form, which I want to update with the total cost of the purchase. How do I go about doing this? -
taking values from user through signup page using ModelForm in django
I am making a signup page using django ModelForm. models.py from django.db import models from django.forms import ModelForm country_choices=( ('india','INDIA'), ('egypt','EGYPT'), ('germany','GERMANY'), ('afghanistan','AFGHANISTAN'), ('switzerland','SWITZERLAND'), ('usa','USA'), ('mexico','MEXICO'), ) class user(models.Model): uid=models.IntegerField(unique=True,default=0) uname=models.CharField(max_length=50) email=models.EmailField() password=models.CharField(max_length=20) phoneno=models.IntegerField(default=0) addr1=models.CharField(max_length=50) addr2=models.CharField(max_length=50) city=models.CharField(max_length=20) state=models.CharField(max_length=20) country=models.CharField(max_length=20,choices=country_choices) pincode=models.IntegerField(default=0) securityq=models.CharField(max_length=100) securitya=models.CharField(max_length=100) def __unicode__(self): return self.uid,self.uname class Meta: db_table="user" class userForm(ModelForm): class Meta: model= user fields= ['uid','uname','email','password','phoneno','addr1','addr2','city','state','country','pincode','securityq','securitya'] views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .models import userForm def homepage(request): return render(request,'student/homepage.html',) def signuppage(request): return render(request,'student/signuppage.html',) def get_userdetails(request): if request.method=='POST': form=userForm(request.POST) if form.is_valid(): new_form=form.save() return HttpResponseRedirect('student/signuppage.html') else: form=userForm() return render(request,'student/homepage.html',{'form':form}) signuppage.html {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>Sign Up</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="{% static 'student/signupcss.css' %}" /> </head> <body> <div class="container"> <section id="content"> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <h1>Create an Account</h1> {{form}} <input type="submit" value="Submit" /> </form> </section> </div> </body> </html> But it displays a blank form with only "Create my account" and a "Submit" button when i access /student/signuppage.html why is that? Do i need to make forms.py with Modelforms also?...if yes then what would i put inside that? -
Django generate url in template
I'm new to Django. I have create pages app which hosts static files like home, about, etc In the urls.py of pages app, I have defined url to access Home class on /pages from django.conf.urls import url from . import views app_name = 'pages' urlpatterns = [ url(r'^$', views.HomeView.as_view(), name='home') ] and included in myapp/urls.py urlpatterns = [ url('^', include('pages.urls')), url(r'^pages/', include('pages.urls')), ] I have included two patterns to set url(r'^$', views.HomeView.as_view(), name='home') of pages app to be access by / (root) and also using pages/home Question: How to generate url in template? Generating url in template from pages like {% url 'home' %} is working fine and is accessible usingpages/home` But, I have a template file base.html outside of all apps which serves as basic structure for all app templates using `{% extends 'base.html' %} When I generate url in base.html like `{% url 'home' %} is gives error as Reverse for 'home' not found. 'home' is not a valid view function or pattern name. I even tried {% url 'pages/home' %} and {% url 'pages.home' %}` but gives same error. -
integrating django 1.11 with a legacy database
hi guys I'm trying to read data from a legacy database with django 1.11. I used inspectdb to save the database model to my app directory. but anytime I try to open django shell or runserver I get this error ValueError: source code string cannot contain null bytes please can anybody help me solve this error so I could read data from the database. my models: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from __future__ import unicode_literals from django.db import models class JustAccount(models.Model): id = models.IntegerField(primary_key=True) # AutoField? account_name = models.CharField(db_column='Account_name', max_length=100) # Field name made lowercase. account_number = models.IntegerField(db_column='Account_number') # Field name made lowercase. ammount = models.FloatField(db_column='Ammount') # Field name made lowercase. class Meta: managed = False db_table = 'just_account' -
Displaying Images in Django - Setting up urls.py
I apologize if this is a duplicate. I have been scouring the web and tried multiple solutions. I have built an image uploader that is uploading the images to the correct location but, I think I have something in my urls.py that is keeping me from being able to display the images. The commented lines are attempts i have made but i am having no luck. urls.py: from django.conf.urls import url from . import views from django.conf import settings from django.conf.urls.static import static app_name = 'orders' urlpatterns = [ url(r'^$',views.index,name='index'), url(r'^invoice/$', views.invoice, name='invoice'), url(r'^photo/$', views.UploadView.as_view()), #static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT), #static(r'^media/', document_root=settings.MEDIA_ROOT), #url("^media/(?P<path>.*)$","django.views.static.serve",{"document_root": settings.MEDIA_ROOT}), url(r'^catalog/$', views.catalog, name='catalog'), url(r'^postStampsShipments/$', views.postStampsShipments, name='postStampsShipments'), url(r'^catalog/(?P<SKU>[^/]+)/$', views.catalogDetail, name='catalogDetail'), url(r'^catalogchange/(?P<SKU>[^/]+)/$', views.catalogChange, name='catalogChange'), url(r'^updateOSTKCat/$', views.updateCatalogOSTK, name='OSTKCat'), url(r'^items/$', views.item, name='items'), url(r'^items/(?P<SKU>[^/]+)/$', views.itemDetail, name='itemDetail'), url(r'^inventory/$', views.inventory, name='inventory'), url(r'^inventoryChange/$', views.inventoryChange, name = 'inventoryChange'), url(r'^test/$', views.test, name='test'), url(r'^genBarcode/$', views.genBarcode, name='genBarcode'), url(r'^barcode/$', views.barcode, name='barcode'), url(r'^(?P<retailOrderNumber>[^/]+)/', views.orderDetail,name = 'Detail'), url(r'^(?P<retailOrderNumber>[^/]+)/shipments/', views.shipments, name='shipments'),] View: def itemDetail(request,SKU): edit = request.GET.get('edit','') itm = Item.objects.filter(SKU=SKU)[0] vendors = Vendor.objects.all() cat = Category.objects.all() template = loader.get_template('orders/itemDetail.html') context = { 'itemDetail':itm,'SKU':SKU,'edit':edit,'vendors':vendors,'cat':cat } return HttpResponse(template.render(context, request)) settings.py: MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Code in template: <td>{% load static %} {{ img.image.url }} <img src="{{ img.image.url }}"> </td> Usual error i am seeing: … -
Abbreviate month name in django
how can you abbreviate month names in a django project so you can display them on the website.how can you abbreviate month names in a django project so you can display them on the website.how can you abbreviate month names in a django project so you can display them on the website.how can you abbreviate month names in a django project so you can display them on the website.how can you abbreviate month names in a django project so you can display them on the website.how can you abbreviate month names in a django project so you can display them on the website.how can you abbreviate month names in a django project so you can display them on the website.how can you abbreviate month names in a django project so you can display them on the website.how can you abbreviate month names in a django project so you can display them on the website.how can you abbreviate month names in a django project so you can display them on the website. -
Django: Validating data with protection against race conditions
I am writing a Django application for booking certain resources. My reservation model is more complicated, but think of a hotel room where you have a check-in and a check-out date. Clearly, each new reservation needs to be checked against conflicting data in the DB and there might be a race condition, if two conflicting reservations are entered simultaneously. This is what I did: # q: unevaluated QuerySet that pulls conflicting reservations from DB # r: new reservation object with transaction.atomic(): if not q.exists(): # no conflicts, if empty r.save() My questions: Is this correct, i.e. does it preserve data integrity? Is there a native Django way (no raw SQL) to insert the integrity check right into the database? I assume this would be the best way to do it in order to prevent any possible way of invalid data entering the DB? If there is no way to do it at database level, where do I tie this into Django so that I catch all or most ways to add new objects to the DB? -
django manage two types of users
I have an app where two type of users are there, frontend and backend user. Frontend user will signup and can login into the app. Similarly admin user can login in backend. There is no similarity between these two type of users. In this case new frontend model (separate table) is required to manage (signup/login ) frontend users, I am guessing it. so, how to achieve this, any suggestions ? -
Is it possible to apply slicing to django function on template?
I´m trying to make a whatsapp button but I´m having problems with the trailing slash at the end on the href. Whatsapp renders wrongly with the trailing slash. I´m using wagtail and puput. I´d like to do it on template only because wagtail and puput are addons on divio. If I install them separatedly, I would have to remake my website, so I can´t change models.py. I´m using {% canonical_url entry %} for the href. What I´d like to have would be something like {% canonical_url|slice:":-1" entry %} They provide full_url placeholder, but it doesn´t add date to link. It gives foo.com/slug instead of foo.com/2017/09/01/slug so everything gets rendered wrong too. Any suggestions? Thanks! -
django-rest-framework JSON POST, request.data throws cannot access body after reading from request's data stream
I'm tring to build a REST api using Django-REST-Framework and python 3.6, But facing an issue with POST requests I can successfully POST json data using postman to an endpoint with content-type set to "application/json" and read it as a dict by doing request.data. This works if I start the server by running python manage.py runserver However, When I'm debugging on Visual Studio Code , Django's standard HttpRequest object does not get overridden by django-rest-framework's enhanced Request object and raises RawPostDataException("You cannot access body after reading from request's data stream") views.py @csrf_exempt @api_view(['GET', 'POST']) @parser_classes((JSONParser,)) def customers(request): received_data = request.data Middlewares defined in settings.py MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Installed apps in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_mysql', 'api', 'installer', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'django_celery_beat', ] VS code's launch.json { "name": "Django", "type": "python", "request": "launch", "stopOnEntry": false, "pythonPath": "/Users/bharath/miniconda3/envs/shopify/bin/python", "program": "${workspaceRoot}/backend/manage.py", "cwd": "${workspaceRoot}/backend", "args": [ "runserver", "--noreload", "--nothreading", "--no-color" ], "env": {}, "envFile": "${workspaceRoot}/.env", "debugOptions": [ "WaitOnAbnormalExit", "WaitOnNormalExit", "RedirectOutput", "DjangoDebugging" ] }, -
Django requests with ajax
I working on a simple mvc application where I have to submit forms with ajax. Then I create a class with purpose to manage all requests from specific module class Produto(View): template_name = 'produto/index.html' def get(self, request): context = { 'modulos': CELLO_APPS, 'modulo': 'Produtos' } return render(request, self.template_name, context) def post(self, request): if request.is_ajax() and request.method == "POST": return JsonResponse({'FOO': 'BAR'}) else: raise Http404 this looks pretty logical to me, but it doesn't work and raise an error missing 1 required positional argument: 'request' the only way I could solve this problem was setting post method as static class Produto(View): template_name = 'produto/index.html' def get(self, request): context = { 'modulos': CELLO_APPS, 'modulo': 'Produtos' } return render(request, self.template_name, context) def post(request): if request.is_ajax() and request.method == "POST": return JsonResponse({'FOO': 'BAR'}) else: raise Http404 So I have two doubts: 1- How can I create a single class with many functions accessible by ajax? 2- Would be this the best or recommended way to manage those views? (Considering this application can grow a lot in the future) -
Django rest framework token based authentication, tokens are visible in http request header
I have implemented token based authentication using django rest framework. But tokens are visible in HTTP requests header when seen using browser's developers tools. And I'm able to fetch private data from API with help of Postman using this token. Thus I feel this is not a secure way for authentication. My questions is that are tokens visible in HTTP request header for every token based authentication. If no, please tell me which one should I use. -
DRF Add user to team 'group''
I have a problem with serializer. I can create a team and add existing user who creates team 'group' to this team simultaneously. But I can't add another users to team later. I'm sending rest with group name and another user, but I receive only user who founded the team. Also no changes in DB. I use django.auth user whose I extend. Relations between User and Team are manyToMany. Should this be done in a different way? Here is my code: models.py class User(AbstractUser, GuardianUserMixin): pass class Team(models.Model): name = models.CharField(max_length=150) users = models.ManyToManyField('webAPI.User', related_name='users') class Meta: permissions = ( ("is_team_admin", "Is team admin"), ("is_team_member", "Is team member") ) serializers.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): user = User(**validated_data) user.set_password(validated_data['password']) user.save() return user def update(self, instance, validated_data): if 'password' in validated_data: password = validated_data.pop('password') instance.set_password(password) return super(UserSerializer, self).update(instance, validated_data) class Meta: model = User fields = ('url', 'id', 'username', 'password', 'first_name', 'last_name') class TeamSerializer(serializers.ModelSerializer): users = UserSerializer(many=True, read_only=True) class Meta: model = Team fields = ('url', 'id', 'name', 'users') views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def get_permissions(self): if self.request.method == 'POST': self.permission_classes = (permissions.AllowAny, ) return super(UserViewSet, self).get_permissions() class TeamViewSet(viewsets.ModelViewSet): queryset = Team.objects.all() serializer_class = … -
`Django administration` to the custom title?
In django admin panel, I have a requirement, how can I change the: Django administration to the custom title? I followed a post, but it do not give the clear steps. I copy the django/contrib/admin/templates to my project /templates/admin, and changed the /templates/admin/base_site.html: <h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django11 administration') }}</a></h1> You see, I changed the Django to Django11, but however in the browser, it do not change at all. The other post on stackoverflow steps are punch-drunk, so who can tell me what should I do more to my requirement? is there need any configurations of my project settings? or something else? -
Django Create a user using only Email and set as inactive
In my app I have 3 kind of users with different permissions. HR, Employees and candidate. I would like to be able to create a User employee providing only its email ans set it as inactive And when the employee sign in into the app he setup a his first name, last name and a password and become Active on the app I am starting in django and have really no idea how to do it; I started the authentication process using the documentation and I get to : views.py : from django.shortcuts import render from .forms import HRForm, CandidateForm, EmployeeForm from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import authenticate,login,logout from django.contrib.auth.backends import ModelBackend from .models import MyUser def registerEmployee(request): registered = False if request.method == "POST": Employee_form = EmployeeForm(data=request.POST) if Employee_form.is_valid(): user = Employee_form.save() user.set_password(user.password) user.is_employee = True user.save() registered = True else: print("Error!") else: Employee_form = EmployeeForm() return render(request,'Employee_registration_form.html', {'Employee_form':Employee_form, 'registered':registered}) Could you please help me or give me direction to dive in ? Thx you ;) -
how to send just one part of an object to template in django
I want to send just one part of an object to template. I Have 2 models like below: class Person(models.Model): name = models.CharField(max_legth=50) sure_name = models.CharFiled(max_length=50) class Office(models.Model): location = models.CharField(max_legth=50) and I also created a model like below: class PersonOffice(models.Model): person = models.ForeignKey(Person) office = models.ForeignKey(Office) now, when I take data from database, by PersonOffice.objects.all(),the data is like below: { { "pk": 0, "person": { "pk":0, "name":"Harry", "sure_name":"Potter" }, "office":{ "pk":5, "Toronto" } }, { "pk": 1, "person": { "pk":6, "name":"John", "sure_name":"Kelly" }, "office":{ "pk":6, "NewYork" } } } I want to send just offices to the template by render function. How can I do it? thanks -
Unable to disable CSRF check in django 1.10
I am using django-1.10 for my project and i want o disable the CSRF check in my project. for this what i Did is that I created a CSRFDiable middleware and added this in middlewares after CommonMiddleWare. This same process worked for me in django 1.8 but in django 1.10 it is not working. I tried removing django.middleware.csrf.CsrfViewMiddleware also but it doesn't work for me. The middleware class is as below class DisableCSRF(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_request(self, request): setattr(request, '_dont_enforce_csrf_checks', True) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'common.middlewares.DisableCSRF', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] The error i am getting on POST request is { "detail": "CSRF Failed: CSRF token missing or incorrect." }