Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: ModelForm and show data on the same url
I'm new to django and trying to create my first app and I think I might need some little help :) I have a ModelForm on a site to submit and want to show the data on the same page. I'm having trouble to set up two functions on the same page, I think i might have to use a class and set it in urls.py but I'm not able to make it work :( the code looks like this: forms.py: from django import forms from .models import Eintrag class NameForm(forms.ModelForm): class Meta: model = Eintrag fields = ['Anmeldung', 'Essen'] urls.py from django.urls import path from . import views app_name = 'form' urlpatterns = [ path('', views.get_name, name='form'), ] views.py from django.shortcuts import render from django.utils import timezone from django.contrib.auth.decorators import login_required from .forms import NameForm from .models import Eintrag @login_required() def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): eintrag = form.save(commit=False) # process the data in form.cleaned_data as required # ... # redirect to … -
Django2 Let user connect google analytics account - Our app will read their data
What is the necessary steps to let the user connect their google analytics account to our Django-website. We need to read their data to trigger specific events for each user. Would be very happy if someone could help with a checklist of the basic steps we need to take to build it. Thanks, Elias -
Refreshing <div> in django but auto refreshing the whole template
I tried to implement the auto-refreshing using this post But the problem it refreshes the complete template instead of just refreshing the target div id. urls.py urlpatterns = [ url(r'^test/', views.test, name='test') ] views.py def test(request): acc_list = AccModel.objects.order_by('-updated') gps_list = GpsModel.objects.order_by('-updated') obj_dict = {'accVal': acc_list, 'gpsVal': gps_list} return render_to_response('appTwo/test.html', context=obj_dict) test.html ....<div id="test"> <h1>{{ gpsVal.0.latValue }}</h1> </div>..... JS Function: function refresh() { $.ajax({ url: '{% url 'test' %}', success: function(data) { $('#test').html(data); } }); setTimeout(refresh, 10000); } $(function(){ refresh(); }); Also, another problem is that no matter what value I give for "setTimeout" it refreshes very frequently. -
Reverse for '' not found. '' is not a valid view function or pattern name - Django App
I am getting the above error in my django app it was working fine earlier. I can't figure out the error after 2 hours. views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request,'dashboard/index.html') urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$',views.index,name='index'), ] dashboard/index.html {% extends 'layout.html' %} {% load staticfiles %} {% block content %} <div class="dash_home"> <p>HELLO</p> </div> {% endblock %} -
django creating a splash page from templates
I am trying to create a default splash page from the templates and I keep getting an error that my template does not exist. >>> import django >>> django.VERSION (2, 0, 5, 'final', 0) Error: Exception Type: TemplateDoesNotExist Session: root@localhost:/home/robin/www/trader# ls admin buy db.sqlite3 manage.py manager __pycache__ sell templates trader views.py root@localhost:/home/robin/www/trader# cat trader/urls.py #from django.contrib import admin from django.urls import path #from django.conf.urls import patterns, url, include #from django.views.generic import TemplateView from . import views app_name = 'trader' urlpatterns = [ path('', views.index, name='index'), # path('admin/', admin.site.urls), #url(r"^$", trader, {"template": "index.html"}), # url(r'^buy/', include('buy.urls')), ] root@localhost:/home/robin/www/trader# cat trader/views.py from django.shortcuts import render from django.http import Http404 from django.http import HttpResponse from django.template import loader def index(request): #return HttpResponse('<p>Hello Index from trader/views.py</p>') return render(request, 'trader/index.html') root@localhost:/home/robin/www/trader# ls templates/ buy manager sell trader root@localhost:/home/robin/www/trader# cat templates/trader/index.html <a>trader templates index</a> root@localhost:/home/robin/www/trader# cat trader/settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'xxx' DEBUG = True ALLOWED_HOSTS = ['tradercoinz.com'] INSTALLED_APPS = [ 'trader', 'buy', 'sell', 'manager', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'trader.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', … -
django Queryset exclude() multiple data
i have database scheme like this. # periode +------+--------------+--------------+ | id | from | to | +------+--------------+--------------+ | 1 | 2018-04-12 | 2018-05-11 | | 2 | 2018-05-12 | 2018-06-11 | +------+--------------+--------------+ # foo +------+---------+ | id | name | +------+---------+ | 1 | John | | 2 | Doe | | 3 | Trodi | | 4 | son | | 5 | Alex | +------+---------+ #bar +------+---------------+--------------+ | id | employee_id | periode_id | +------+---------------+--------------+ | 1 | 1 |1 | | 2 | 2 |1 | | 3 | 1 |2 | | 4 | 3 |1 | +------+---------------+--------------+ I need to show employee that not in salary. for now I do like this queryset=Bar.objects.all().filter(periode_id=1) result=Foo.objects.exclude(id=queryset) but its fail, how do filter employee list not in salary?... -
old field json to json postgres 9.5
In my model I have oldJSONField, I'm trying to change it to JSONField: I did the following steps: 1. add the jsonField to the model 2. makemigrations 3. in the migration file, and copy between the fields 4. makemigrations 5. delete the old field 6. makemigration, migrate so far everything is good, but when i'm trying to change the new field name to old field name, all the rows in that column changed to null. dependencies = [ ('book', '0010_auto_20180513_1341'), ] operations = [ migrations.RenameField( model_name='book', old_name='new_names', new_name='names', ) what is the way to do it properly? thanks -
Django Unit Testing (with DRF): How to test a Passwordresetview?
I'm currently trying to write my unittest for a successfull password reset. TLDR: I can't figure out how to handle the injection of the form data in the post request in the setpassword view. For context, let me give you my code first, since a line of code speaks more than 1000 words. accounts/api/views.py: class PasswordResetView(generics.GenericAPIView): """(POST) Expects email. Sends a password reset mail to email.""" permission_classes = (permissions.AllowAny,) serializer_class = PasswordResetSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): user = User.objects.get(email=serializer.data['email']) if user.is_active and user.has_usable_password(): send_password_reset_email(user, request) return Response( {"detail": "A password reset email has been send."}, status=status.HTTP_204_NO_CONTENT ) else: return Response( {"detail": "This users password can't be reset."}, status=status.HTTP_406_NOT_ACCEPTABLE ) accounts/api/urls.py: url(r'^password_reset/$', views.PasswordResetView.as_view(), name="password_reset"), accounts/api/serializers.py: class PasswordResetSerializer(serializers.Serializer): email = serializers.EmailField() def validate_email(self, value): if User.objects.filter(email__iexact=value).exists(): return value else: raise serializers.ValidationError("Email not found.") accounts/utils.py: from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.contrib.sites.shortcuts import get_current_site from django.utils import six from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from templated_email import send_templated_mail password_reset_token = PasswordResetTokenGenerator() def build_email_context(user_obj, request): current_site = get_current_site(request) context = { "name": "", "domain": current_site.domain, "uid": urlsafe_base64_encode(force_bytes(user_obj.pk)), 'token': password_reset_token.make_token(user_obj) } if user_obj.name != "": context["name"]: " " + user_obj.name return context def send_password_reset_email(user_obj, request): context = build_email_context(user_obj, … -
Push Notifications with time not default
When I am using https://github.com/olucurious/PyFCM this PyFCM for push notifications for web site and app but one thing is pending according to given link: How can I pass push notifications with time mean 1 hour or 2 hours. Now I am using python for django. # Send to single device. from pyfcm import FCMNotification push_service = FCMNotification(api_key="<api-key>") # OR initialize with proxies proxy_dict = { "http" : "http://127.0.0.1", "https" : "http://127.0.0.1", } push_service = FCMNotification(api_key="<api-key>", proxy_dict=proxy_dict) # Your api-key can be gotten from: https://console.firebase.google.com/project/<project-name>/settings/cloudmessaging registration_id = "<device registration_id>" message_title = "Uber update" message_body = "Hi john, your customized news for today is ready" result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body) # Send to multiple devices by passing a list of ids. registration_ids = ["<device registration_id 1>", "<device registration_id 2>", ...] message_title = "Uber update" message_body = "Hope you're having fun this weekend, don't forget to check today's news" result = push_service.notify_multiple_devices(registration_ids=registration_ids, message_title=message_title, message_body=message_body) print result I have created a new function for this setting. But we need to send push notifications to other users those are exist in same user setting with 1 hour not for all message . How can I set timing for push notification and what is api_key according … -
simple django activity app
I need an idea or example on how to create a simple activity app that will update users with activities of company they are following . For example i have a model Class Company(models.Model): followers=models.ManyToManyField(User,null=True) companyname=models.CharField(max_length=250,null=True) Users can follow a company .I want users to be updated with the activities of companies they are following . Please give me an idea on how to go about this. I have research , but i could not really get solution to this . -
use searializer field in template Django Rest Framework
I'm new to Django Rest Framework and writing first API application. my contacts/models.py class Contact(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) class Meta: db_table = 'contacts' def full_name(self): return self.first_name + ' ' + self.last_name def __str__(self): return self.full_name() class ContactEmail(models.Model): contact = models.ForeignKey(Contact, on_delete=models.CASCADE) email = models.EmailField() primary = models.BooleanField(default=False) class Meta: db_table = 'contact_emails' def __str__(self): return self.email contacts/searializers.py class ContactSerializer(serializers.HyperlinkedModelSerializer): primary_email = serializers.SerializerMethodField() class Meta: model = Contact fields = ('url', 'full_name', 'date_of_birth', 'primary_email') def get_primary_email(self, obj): primary_email = obj.contactemail_set.filter(primary=True).first() if primary_email: return primary_email.email return '' contacts/views.py class ContactViewSet(viewsets.ModelViewSet): queryset = Contact.objects.all() serializer_class = ContactSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def perform_create(self, serializer): serializer.save(user_id=self.request.user) class ContactList(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'contacts/list.html' permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def get(self, request): queryset = Contact.objects.all() return Response({'contacts': queryset}) Where ContactViewSet is accessible by http://<ip>:<port>/api/contacts and ContactList is accessible by http://<ip>:<port>/contacts http://<ip>:<port>/api/contacts is giving primary_email in the json response but it prints nothing on using in list.html {{ contact.primary_email }} Can't I use Serializer fields when using **APIView?** Do I need to rewrite the function in the ContactList() to get primary_email field? -
Django, Funtion view vs Class view Error : Need 2 values to unpack in for loop; got 1.
Something strange happens in mi app. I have 2 views whit the same code. Ones is a funtion view and the other is a class view. why, i wrote the funtion view first, and i want to migrate to a clase view Context: i want to generate a calendar whit the events created by the user on it. so i user "get_context_data" to get the calendar values and the values from the events in my DB. views.py funtion or class definition... some code.... def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(EventCreate, self).get_context_data(**kwargs) #Calendar month_name = calendar.month_name[now().month] weekdays = [ header for header in calendar.weekheader(10).split()] cal = calendar.Calendar() cal.setfirstweekday(6) #firstweekday = Sunday = 6 month = [[]] week = 0 month_events = Event.objects.filter(date__year=now().year).filter(date__month=now().month) for day in cal.itermonthdays(now().year, now().month): if day: occurrences = list(filter(lambda e: e.date.day==day, month_events)) else: occurrences = [] month[week].append((day, occurrences)) month[week].append(day) if len(month[week]) == 7: month.append([]) week += 1 context.update({'year': now().year, 'month_name': month_name, 'month': month, 'weekdays': weekdays}) return context calendar.html <h1>{{ month_name }}</h1> <table class="table"> <thead> {% for weekday in weekdays %} <th>{{ weekday }}</th> {% endfor %} </thead> <tbody> {% for week in month %} <tr> {% for days, occurrences … -
Distributing 'clean' Django project source code
I'm currently working on a small project in Django, which I would later like to publish on github, send to someone in a zip archive etc. While testing my app, I make changes to the server to see how it behaves. Now, if I want to publish my source code, I don't want it to contain any garbage I might have generated during the development process. Basically, whoever receives the code should have a minimal, clean version of it, and at the same time should be able to work with it out of the box. What is the best way to do this? Should I make migrations before publishing my code? Are there any standard practices? -
Navigation on one site using href="#About us" does not work on smaller devices
In my django project, I am trying to build a menu for navigation on one single site. The navigation should be done by href="#about us" The menu has three sizes, one for big screens (PC), one for medium screens (Tablets), and one for small screens (Phones). The navigation works on PC size menu, but does not work on the other ones. To be clear, all of the menus redirects the user to something like mywebsite.com/info#about us, but just the PC menu actually scrolls the site. There, I fill the menus with some content from a database: {% block big-menu %} {% for faq in question_list %} <a href="#{{faq.question}}" class="w3-button w3-bar-item w3-hover-text-blue">{{faq.question}}</a> {% endfor %} {% endblock %} {% block small-menu %} {% for faq in question_list %} <a href="#{{faq.question}}" class="w3-button w3-bar-item w3-hover-text-blue">{{faq.question}}</a> {% endfor %} {% endblock %} And there is the template for the menus: <div class="w3-sidebar w3-bar-block w3-collapse w3-card w3-animate-right w3-hide-small" style="width:300px;right:0;top:0;" id="mySidebar"> <button class="w3-bar-item w3-button w3-large w3-hide-large" onclick="w3_close()"><h3>Menu &times;</h3></button> <a class="w3-bar-item w3-large w3-hide-small w3-hide-medium"><h3>Menu</h3></a> {% block big-menu %} {% endblock %} </div> <div class="w3-bar-block w3-collapse w3-animate-right w3-hide-large w3-hide-medium w3-light-gray" style="display:none;" id="smallSidebar"> <a class="w3-bar-item w3-large"><h3>Menu</h3></a> {% block small-menu %} {% endblock %} </div> And there I assign ids … -
form is not valide django
when i send data from a post form rzlt always undone ithink it's bcz the form is unvalide def addit(request): if request.method == 'POST': target="undone" forms = employeeForm(request.POST or None,request.FILES or None) if forms.is_valid(): em=models.Employee em.fname=forms.cleaned_data["fname"] em.cne=forms.cleaned_data["cne"] em.lname=forms.cleaned_data["lname"] em.division=forms.cleaned_data["division"] em.pic=forms.cleaned_data["pic"] em.salary=forms.cleaned_data["salary"] em.save target="done" return render(request, "home.html",{"target":target} ) models class Employee(models.Model): fname=models.CharField(max_length=250) lname=models.CharField(max_length=250) cne=models.CharField(max_length=250) division=models.CharField(max_length=250) salary=models.FloatField() pic=models.FileField(upload_to="static/img") rzl hi{{target}} -
How can I add a model in custom CBV view?
My custom CBV is working fine but When I open a page it displays nothing. All I want is when a get() is called it displays a Blog Post and form underneath the post and when form is filled it calls the post() and save it in the database. but when I open a blog post it displays nothing. before moving to Custom CBV I was using the (detailView) everything was fine. class DetailView(View): form_class = CommentForm template_name = "blogs/details.html" model = BLOG def get(self, request, slug): forms = self.form_class(None) blogs = self.model context = {'forms': forms, "blogs":blogs} return render(request, self.template_name, context) def post(self, request): forms = self.form_class(request.POST) if forms.is_valid(): user_comment = forms.save(commit=False) Name = cleaned_data["Name"] Email = cleaned_data["Name"] comment = cleaned_data['comment'] user_comment.save() -
`View().as_view` does not raise an error responding to get and post request
In Django Docs django/views/generic/base.py I am unable to understand the following code. if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don't do that." % (key, cls.__name__)) in class View: http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'] def __init__(self, **kwargs): for key, value in kwargs.items(): # smart setattr(self, key, value) @classonlymethod def as_view(cls, **initkwargs): """Main entry point for a request-response process.""" for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don't do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError("%s() received an invalid keyword %r. as_view " "only accepts arguments that are already " "attributes of the class." % (cls.__name__, key)) The class attribute is http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'], so if pass in a get or post request, as_view would raise an error. However, View().as_view does not raise an error responding to get and post request. What's wrong with my guess? -
django how can I change user profile with auth.views.password_change views?
User models has nickname and cell_phone fields. I want to change user password or user nickname at same html template selectively When I try to change the user password with password_change view in auth.views, it works well. However, when I try to change only user nickname with password_change view, it doesnt' work. following is my custom SetPasswordForm and PasswordChangeForm What should I change? class CustomSetPasswordForm(forms.Form): """ A form that lets a user change set their password without entering the old password """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } new_password1 = forms.CharField( label=_("New password"), widget=forms.PasswordInput, strip=False, required=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_("New password confirmation"), strip=False, required=False, widget=forms.PasswordInput, ) username = forms.CharField(required=False,) cell_phone = forms.CharField(required=False, widget=forms.NumberInput()) def __init__(self, user, *args, **kwargs): self.user = user super(CustomSetPasswordForm, self).__init__(*args, **kwargs) def clean_new_password2(self): password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if not password1 and password2: pass elif password1 and password2: if password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): password = self.cleaned_data["new_password1"] username = self.cleaned_data['username'] cell_phone = self.cleaned_data['cell_phone'] if username: self.user.username = username if cell_phone: self.user.cell_phone = cell_phone self.user.set_password(password) if commit: self.user.save() return self.user class CustomPasswordChangeForm(CustomSetPasswordForm): """ A form that lets a user change … -
django-rest save array of data to db
hi im trying to save a form data into db. i provided print of requset.data for you as you see requirement have two items. i want to save each item in database i use for loop to save each item of list but the loop save each character like h-e-l,... in table row... where is my mistake ... thanks also print of request.data.get('requirement') will retun second item this is print of request.data in sever: <QueryDict: {'requirement': ['hello', 'bye'], 'audience': ['adasd'], 'achievement': ['asdasd'], 'section': ['410101010'], 'title': ['asdasd'], 'mini_description': ['asdad'], 'full_description': ['asdasd'], 'video_length': ['10101'], 'video_level': ['P'], 'price': [''], 'free': ['true'], 'image': [<InMemoryUploadedFile: p.gif (image/gif)>]}> view: class StoreCreateAPIView(generics.CreateAPIView): parser_classes = (MultiPartParser, FormParser) permission_classes = [IsAuthenticated] def perform_create(self, serializer): serializer.save(author=self.request.user) def post(self, request, *args, **kwargs): if request.method == 'POST': print(request.data) file_serial = ProductSerializer(data=request.data, context={"request": request}) if file_serial.is_valid(): file_serial.save(author_id=request.user.id) requirement = request.data['requirement'] audience = request.data.get('audience') achievement = request.data.get('achievement') sections = request.data.get('section') print(request.data['requirement']) pid = file_serial.data.get('product_id') for item in requirement : req = ProductRequiredItems( item = item, product_id = pid ) req.save() -
Django admin inline issue with foreignkey
I have a model used for descriptions in different languages: class Description(models.Model): language = models.IntegerField(default=0) description = models.TextField() class Meta: db_table = 'Description' unique_together = (("id", "language"),) So this class should be used in many other classes for translating descriptions like this: class Actions(models.Model): useraction = models.IntegerField() message = models.ForeignKey('Description', on_delete=models.SET_NULL, db_column='message', null=True) class Meta: db_table = 'Actions' Then I tried to implement it in the damin.py so that I canmaintain the Actions-Model and directly the corresponding description: class DescriptionInline(admin.StackedInline): model = Description class DescriptionAdmin(admin.ModelAdmin): pass class ActionsAdmin(admin.ModelAdmin): inlines = [ DescriptionInline, ] But that trows the following exception when running the server: ERRORS: : (admin.E202) 'manageta.Description' has no ForeignKey to 'manageta.Actions'. Since I use the Description-Model for multiple other models I cannot set the foreignkey from it the other models but the other way around like shown above. Can anybody tell me what I did wrong? Thanks Key -
Django channels integrating with django
I'm following django channels tutorial in order to integrate it with django. But, at one point I confronted with error which I can't solve. In terminal Django says: [Errno 111] Connect call failed ('127.0.0.1', 6379) I think that problem is about with these lines in tutorial: We will use a channel layer that uses Redis as its backing store. To start a Redis server on port 6379, run the following command: $ docker run -p 6379:6379 -d redis:2.8 I'm working in Linux Ubuntu 17.04 and can't run command shown in above. When I run that command ubuntu terminal says: docker: command not found Result is still the same after installing 'docker' with 'sudo apt-get install docker'. How can I solve this problem? Is there other way to start redis server on specified port without installing docker? -
InvalidRequestError: Charge has already been captured
Getting this error on my stripe payment: InvalidRequestError at /advertise/pay/CEMJmXl/ Request req_BGP6UZUem3VHjH: Charge ch_1CRDAyDMGCr2H3QWTBY5jfBN has already been captured. I'm only using a testing environment, with my STRIPE_TEST_PUBLIC_KEY and STRIPE_TEST_SECRET_KEY. The card number I'm using is the test card number for Visa (seen in https://stripe.com/docs/testing) Here's my view: def pay(request, hash): ad = get_object_or_404(AdvertisePost, hash=hash) amount = ad.total_price * 100 # Set your secret key: remember to change this to your live secret key in production # See your keys here: https://dashboard.stripe.com/account/apikeys # stripe.api_key = "sk_test_nxhH2wdK2kTkaxzbtVpv0MOBW" stripe.api_key = "sk_test_nxhH2wdK2kTkaxzbtVpv0MOBW" # Token is created using Checkout or Elements! # Get the payment token ID submitted by the form: if request.POST.get('stripeToken'): token = request.POST.get('stripeToken') charge = stripe.Charge.create( amount=amount, currency='usd', description='Boosted Post', source=token, ) charge.capture() return HttpResponseRedirect('/') else: pass print(request.POST) context = { 'amount': amount, 'ad': ad } return render(request, 'advertising/pay.html', context) Any idea why I'm getting the error? -
Unable to pass User Model's first_name and last_name data to a template
I am trying to construct a user profile page for my project, hence I need to access to user Model's data like first_name and last_name. But for some reason I can access the username and email field but not the first_name and last_name. When I call these fields from my template, nothing displays. <table class="table-responsive"> <tr> <td>Username</td> <td>{{ user.get_username }}</td> </tr> <tr> <td>First Name</td> <td>{{ user.first_name }}</td> </tr> <tr> <td>Last Name</td> <td>{{ user.last_name }}</td> </tr> <tr> <td>Email</td> <td>{{ user.email }}</td> </tr> </table> My profile_view.py def profile_view(request): args = {'user' : request.user} return render(request, 'user_account/profile.html', args) I've tried using the functions like user.get_full_name but that doesn't work either. thanking you in advance. -
Content type query filter by object value
I use Django 2.0.0 and have the following database structure: class Project(models.Model): name = models.CharField(_(u'Name'), max_length=32) class Domain(models.Model): project = models.ForeignKey('projects.Project', on_delete=models.CASCADE) tool_result = GenericRelation('projects.ToolResult') class ToolResult(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') I want to get all ToolResults filter based on content_type object project. ToolResult.objects.filter(content_type=ContentType.objects.get_for_model(Domain), content_object__project__in=[1, 2]) I tried like this but it is not working. I have about 500k domain records and 3kk ToolResults records. That makes not possible to iterate objects. How do I can do this effective ? -
When attempting to save from a serializer getting error - Unable to get repr for class
I ma trying to understand why I am getting the error for my serializer Unable to get repr for <class 'Job.models.modelJob'> This is what my job looks like class modelJob(models.Model): employer = models.ForeignKey(modelEmployer,on_delete=models.CASCADE,null=True,default=None,blank=True) title = models.CharField(max_length=200, unique=False,blank=False,null=True) moreInfo = models.CharField(max_length=500, unique=False,blank=False,null=True) imageA = models.ImageField(upload_to='images/', default='',null=True) imageB = models.ImageField(upload_to='images/', This is what I am posting to it { "title" : "Plumbing", "moreInfo" : "A", } This is my serializer class Serializer_CreateJob(serializers.ModelSerializer): class Meta: model = modelJob fields = [ 'title', 'moreInfo', ] This is my view class Test_CreateAPIView(CreateAPIView): serializer_class = Serializer_CreateJob permission_classes = (permissions.AllowAny,) def post(self, request, format=None): emp = modelEmployer.objects.all()[0]; serializer = self.serializer_class(data=request.data) if serializer.is_valid(): modeljob = serializer.save();#------>Not getting back the object return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) From what I understand modeljob = serializer.save(); is suppose to return back a created object but it doesnt. I know i can overwrite create(self, validated_data) and return back an object but in this case I would simply like to create an object. Why is save() not returning back an object ? Any suggestions ?