Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'create_song' not found. 'create_song' is not a valid view function or pattern name
I have a Django project in which the page that should load to show the album that has just been added, does not. It should go to the primary key for that album (auto generated) with the reference: http://127.0.0.1:8000/music/1/ but instead gives the error: Reverse for 'create_song' not found. 'create_song' is not a valid view function or pattern name. A variant of the same problem, I assume, Is that when I click on the VIEW DETAILS BUTTON (shown below in the index.html) it doesn't load: <div class="caption"> <h2>{{ album.album_title }}</h2> <h4>{{ album.artist }}</h4> <!-- View Details --> <a href="{% url 'music:detail' album.id %}" class="btn btn-primary btn-sm" role="button">View Details</a> <!-- Delete Album --> <form action="#" method="post" style="display: inline;"> {% csrf_token %} <input type="hidden" name="album_id" value="{{ album.id }}" /> <button type="submit" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-trash"></span> </button> </form> The code for the various sections is below: music/templates/music/album_form.html <div class="row"> <div class="col-sm-12 col-md-7"> <div class="panel panel-default"> <div class="panel-body"> <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'music/form_template.html' %} <!-- how form fields and inputs are laid out--> <div class="form-group> <div class="col-sum-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> </div> </div> </div> {% endblock %} music/views.py from django.views … -
How to use active record as DTO to my business objects.
I struggle with this problem for a long time. I searched and searched the whole internet for solution but nothing was acceptable for me. We started a project which looked very simple in terms of business logic required, so I picked Django as a framework to make things easier. The problem got complex and maybe the implementation will be used in a much larger project so I want to decouple my business objects objects from activerecord and I want to use django only as a DB backend and something which uses my objects. The UI is already decoupled from the start, it only calls a REST API provided by the django backend. My problems with an example: I have a Request model which connected to many other models. This request contains some requirement specification related to networks. These networks are associated to a Cloud models. The networks under a cloud will be connected to the reservation which is generated from the request (currently they are connected to the request's nw descriptors to determine the configurations during queries). class Request(Model): ... # bunch_of_stuff_here class NetworkDescriptor(Model): request = ForeignKey(Request) configA = ... configB = ... class Cloud(Model): ... class Network(Model): cloud = … -
Trying to understand JSONField for django postgresql
I'm reading the docs on JSONField, a special postgresql field type. Since I intend to create a custom field that subclasses JSONField, with the added features of being able to convert my Lifts class: class Lifts(object): def __init__(self, series): for serie in series: if type(serie) != LiftSerie: raise TypeError("List passed to constructor should only contain LiftSerie objects") self.series = series class AbstractSerie(object): def __init__(self, activity, amount): self.activity_name = activity.name self.amount = amount def pre_json(self): """A dict that can easily be turned into json.""" pre_json = { self.activity_name: self.amount } return pre_json def __str__(self): return str(self.pre_json()) class LiftSerie(AbstractSerie): def __init__(self, lift, setlist): """ lift should be an instance of LiftActivity. setList is a list containing reps for each set that has been performed. """ if not (isinstance(setlist, collections.Sequence) and not isinstance(setlist, str)): raise TypeError("setlist has to behave as a list and can not be a string.") super().__init__(lift, setlist) I've read here that to_python() and from_db_value() are two methods on the Field class that are involved in loading values from the database and deserializing them. Also, in the docstring of the to_python() method on the Field class, it says that it should be overridden by subclasses. So, I looked in JSONField. Guess … -
Cant get Django debug-toolbar 1.9 to work on django 2.0
I have installed Django debug-toolbar using pip, and added 'debug_toolbar' to the installation app list , but can't manage to get it to work on django 2.0. -
Django serve file to download with CBV
I am trying to serve multiple files in a DetailView. This is the flow: user uploads some docx files in a folder named 'documents' using formsets. In this detailview the admin will be able to see the files and download them. models.py class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) created = models.DateTimeField(auto_now_add=True) number = models.CharField(max_length=100, unique=True) class OrderDoc(models.Model): order = models.ForeignKey(Order) language_source = models.ForeignKey(Language, default=None, null=True) file = models.FileField(upload_to='documents') views.py class OrderUpdateView(LoginRequiredMixin, UpdateView): template_name = 'core/admin_order_update.html' model = Order form_class = OrderForm success_url = reverse_lazy('core:admin_order_list') def get_context_data(self, **kwargs): context = super(OrderUpdateView, self).get_context_data(**kwargs) context['order_documents'] = OrderDoc.objects.filter(order__pk=self.kwargs['pk']) return context admin_order_update.html <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> {% for document in order_documents %} {{ document.file }} {% endfor %} Obviously here document.file shows just the path. I've seen some examples but i don't know how to implement them in cbv. How can i make the files downloadable in detailview? -
Django yearless ranges
I need to store start and ending dates to save holidays. I don't care about the year part of dates, as a holiday will repeat every year. Also I need to be able to query this dates to see if a random datetime is in the range. And even when I don't want years stored, the query must understand that a holiday can start in one year and end next year (i.e. Dec 25th to Jan 4th). Previously I was storing the dates as DateTimeFields, then iterating over each stored holiday and checking if a given target date was inside the dates range. This was made in Python and forced me to evaluate the QuerySets into lists and finally add the value using something like getattr(result, 'is_a_holiday', value) As performance issues have arise I want to move this into an annotation (so I can keep the queryset with select_related and prefetch_related data) and make the database (Postgresql) do the query part, but then I run into the problem that the database considers the year, and thus a date inside a holiday for this year is not considered inside a holiday the previous year or next year. I've already tried django-yearlessdate … -
Applying ckeditor to a textarea
I am trying to add the (inline) CKEditor 5 to an existing django project. I figured I would just use the normal form workflow and simply add the CKEditor to a textarea element inside a form, as via the documentation. <form enctype="multipart/form-data" action="{% url 'some_url' %}" method="post"> {% csrf_token %} {{ message_form.media }} {{ message_form.as_p }} <textarea id="something"></textarea> <input type="submit" value="Post message" class="button-bright button-static" /> </form> <script> InlineEditor .create( document.querySelector( '#something' ) ) .catch( error => { console.error( error ); } ); </script> When I add this to my template the textarea shows up with some of the ckeditor styling applied, and it also shows the inline texteditor, but with all of the buttons greyed out. The only thing I can do is type stuff in the textarea but literally nothing else. I can't use enters and I can't even delete anything I typed by pressing the backspace button either. -
Optimise Configuration for Apche2 for Django Web application with 8 vCPUs and 32 RAM
I'm using 8 VCPUs and 32RAM for one of my Django Web application , Apache2 has been used as web server. And i have configured apache2 as below. I'm not to much proficient in Apache2. Kindly let me know what is optimise configuration of apache2 that I can utilise approx 95% resources of machine. /etc/apache2/mods-available/mpm_event.conf <IfModule mpm_event_module> ServerLimit 4 StartServers 2 MinSpareThreads 50 MaxSpareThreads 100 ThreadsPerChild 50 </IfModule> /etc/apache2/sites-available/000-default.conf WSGIDaemonProcess clip_to_frames processes=2 threads=50 graceful-timeout=300 maximum-requests=5000 queue-timeout=200 -
TypeError: a bytes-like object is required, not 'str' python3
In my project, I'm dynamically writing styles into HTML file. I have recently migrated from python2 to 3. Now it's throwing an error as shown below log: Code Snippet : html_text = markdown(html_content, output_format='html4') css = const.URL_SCHEME + "://" + request_host + '/static/css/pdf.css' css = css.replace('\\', "/") # HTML File Output #print 'Started Html file generated' + const.CRUMBS_TIMESTAMP html_file = open(os.getcwd() + const.MEDIA_UPLOADS + uploaded_file_name + '/output/' + uploaded_file + '.html', "wb") #print(html_file) html_file.write('<style>') html_file.write(urllib.request.urlopen(css).read()) html_file.write('</style>') Error Log : Quit the server with CTRL-BREAK. ('Unexpected error:', <class 'TypeError'>) Traceback (most recent call last): File "C:\Dev\EXE\crumbs_alteryx\alteryx\views.py", line 937, in parser result_upload['filename']) File "C:\Dev\EXE\crumbs_alteryx\alteryx\views.py", line 767, in generate_html html_file.write('<style>') TypeError: a bytes-like object is required, not 'str' -
Need to save the model in admin.py without signals
I need to save the Estimate_id.specs to Estimate. I dont know how I can save this. If I run below admin.py model, I am getting below output. cleaned data {u'item_name': u'Backup server', u'qty': 12.0, 'environment': <Environment: Database server>, u'item': <ItemTemplate: Servers>, u'id': None, u'DELETE': False} items {u'na': u'na'} environment {u'test': 12121, u'XYZ': u'XYZ', u'123': 123} (u'final evnironemnet dic', {u'test': 12121, u'na': u'na', u'XYZ': u'XYZ', u'123': 123}) Servers 282 {u'item_name': u'Backup server', u'qty': 12.0, 'environment': <Environment: Database server>, u'item': <ItemObject: Servers>, u'id': None, u'DELETE': False} id SVT Servers (u'specs', {u'svt_test_sepc': u'scvt_test_spev'}) (u'final estimate dict', {u'test': 12121, u'svt_test_sepc': u'scvt_test_spev', u'XYZ': u'XYZ', u'123': 123, u'na': u'na'}) I am getting the final estimate dict the way I want but now I need to save it to estimate_id.specs but that did not happen. I think I need to use save_model function for this but I don't know how. Any pointers is much appreciated. class AddEnvironmentDetailsInlineForm(forms.ModelForm): class Meta: ... item = forms.ModelChoiceField(queryset=ItemTemplate.objects.all()) estimate = forms.ModelChoiceField(queryset=Estimate.objects.all()) def clean(self): instance = self.cleaned_data['item'] print "cleaned data", self.cleaned_data print "items", self.cleaned_data['item'].specs print "environment", self.cleaned_data['environment'].specs item_specs = self.cleaned_data['item'].specs environment_specs = self.cleaned_data['environment'].specs environment_specs.update(item_specs) print("final evnironemnet dic", environment_specs) print instance fields = [f.name for f in Item._meta.fields] values = dict([(x, getattr(instance, x)) for … -
How to run a Python script on clicking Submit button in HTML using Django?
I am using Django as the framework but I'm pretty new to Django. I have an HTML file with me that is showing up using Django as the framework. I have added a Submit button to the HTML page. I have a python script saved locally on my server. Is there any way to run the python when clicking on the Submit button? Or can this be done when clicking on an image/logo? -
Django Aggregation: Aggregate on relational queryset
Suppose I have following models, which store questions and options for those questions. P.S: I am just writing the basic code just to give you idea. class Question(models.Model): text = models.CharField() class Option(models.Model): text = models.CharField() class QuestionOption(models.Model): question = models.ForeignKey(Question) option = models.ForeignKey(Option) And then I have models which store user Feedback and Options selected for each Question in the Feedback survey. class Feedback(models.Model): full_name = models.CharField() cell_phone = models.CharField() created_at = models.DateTime() class FeedbackOption(models.Model): feedback = models.ForeignKey(Feedback, related_name='feedback_options') option = models.ForeignKey(QuestionOption) Every feedback will have lots of feedback option objects. Now I want to filter all the feedback whose feedback options contain specific QuestionOption object and then perform aggregate query where I am checking if that feedback's FeedbackOptions option text is 'boo' add count. Can i do this in one step, Something like this # lets say i want to filter all feedback with QuestionOption id 1 stats = Feedback.objects.filter(feedback_options__option=1).aggregate( boo=Count(Case(When(feedback_options__option__option__text='boo', then=1))), hoo=Count(Case(When(feedback_options__option__option__text='hoo', then=1)))) It looks like it's applying aggregate on the only feedback option where option id is 1 not the rest of the feedback options for each feedback. -
Upload file using ajax to djangorest api?
I have a ajax call as below. Now I want to post data including file to the url /api/create/project created . $(document).ready(function(){ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $(".project").submit(function(event){ event.preventDefault() var image_file = document.getElementById('content'); var myFile = image_file.files[0]; console.log(myFile); var this_ = $(this); var form = this_.serializeArray(); console.log("form", this_); console.log(form); var formData = this_.serialize(); var temp= { "title": form[1].value, "project_question_content_url": myfile, "deadline_date": form[2].value, "employee": {{ id }}, "course": form[3].value } console.log(temp); $.ajax({ url: "/api/project/create", data: JSON.stringify(temp), beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, method: "POST", contentType: "application/json; charset=utf-8", dataType: 'json', success: function(data){ console.log(data) }, error: function(data){ console.log("error") console.log(data.statusText) console.log(data.status) } }) }); }); Now, How to send file through json in the temp variable? I have … -
How add permissions to a 'POST' or 'PUSH' on Django Rest Framework?
I have a problem with DRF. When I try 'GET', it's usefull, but when I try to 'PUSH' I have an error of unauthorized. How add this authorization? When I try this I already had basic authorization -
How can I manage to assign the button to number I want the user to input?
enter image description here On django, I have this html output and my goal is to, when the user put a number ( "number_card") and press the button it returns severall information about that number.. How can I point the button to the field of the number? -
Why the supervisor make the celery worker changing form running to starting all the time?
backgroud The system is Centos7, which have a python2.x. 1GB memory and single core. I install python3.x , I can code python3 into python3. The django-celery project is based on a virtualenv python3.x,and I had make it well at nginx,uwsgi,mariadb. At least,I think so for no error happend. I try to use supervisor to control the django-celery's worker,like below: command=env/bin/python project/manage.py celeryd -l INFO -n worker_%(process_num)s numprocs=4 process_name=projects_worker_%(process_num)s stdout_logfile=logfile.log etderr_logfile=logfile_err.log Also had make setting about celery events,celery beat,this part is well ,no error happend. Error comes from the part of worker. When I keep the proces big than 1,it would run at first,when I do supervisorctl status,all are running. But when I do the same command to see status once more times,some process status change to starting. So I try more times,I found that:the worker's status would always change from running to starting and then changeing starting to running-- no stop. When I check the supervisor's logfile at tmp/supervisor.log,it shows like: exit status 1; not expected entered runnging state,process has stayed up for > than 1 seconds(startsecs) 'project_worker_0' with pid 2284 Maybe it shows why the worker change status all the time. What's more ,when I change the proces to … -
Django 1.11.4 struct.error: unpack requires a buffer of 4 bytes
So I'm using vagrant to create a working environment. It works on my pc. But when I use my laptop after creating the environment I get this error: ` Traceback (most recent call last): File "manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/usr/local/lib/python3.6/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/usr/local/lib/python3.6/dist-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/lib/python3.6/dist-packages/django/contrib/auth/models.py", line 103, in <module> class Group(models.Model): File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 162, in __new__ new_class.add_to_class(obj_name, obj) File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 331, in add_to_class value.contribute_to_class(cls, name) File "/usr/local/lib/python3.6/dist-packages/django/db/models/fields/related.py", line 1648, in contribute_to_class self.remote_field.through = create_many_to_many_intermediary_model(self, cls) File "/usr/local/lib/python3.6/dist-packages/django/db/models/fields/related.py", line 1104, in create_many_to_many_intermediary_model 'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to}, File "/usr/local/lib/python3.6/dist-packages/django/utils/functional.py", line 162, in __mod__ return six.text_type(self) % rhs File "/usr/local/lib/python3.6/dist-packages/django/utils/functional.py", line 119, in __text_cast return func(*self.__args, **self.__kw) File "/usr/local/lib/python3.6/dist-packages/django/utils/translation/__init__.py", line … -
How to set media full url? (from settings.py django)
I'm in the debugging mode and I want to set default ImageField to return full URLlocalhost:8000/path. Here is current JSON data ... "img": "http://localhost:8000/media/outfits/1/4.png", "tagged_clothes": [ { "cloth_image": "/media/clothes/1/7.png", <- Why is it happening?? And how can I fix it? "id": 6, "b_clothtype": "ETC", Here is Serialiezer class ClothesListSerializer(serializers.ModelSerializer): class Meta: model = Cloth fields = ('cloth_image' ...) <- can't do URL. settings.py MEDIA_URL = '/media/' # if I change this variable as 'localhost:8000/media/', # JSON returns correct URLs but I couldn't see the image. MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media_cdn') urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
what means, Bad HTTP/0.9 request type ('\x03\x00\x00*%à\x00\x00\x00\x00\x00Cookie:'), code 400?
When I get into my server (Django 2.0, host AWS, port: 8000), I find this log, I think it is a scan or an attack from some hacker, is there something I can do against and is it alarming? Not Found: /favicon.ico [27/Dec/2017 22:42:00] "GET /favicon.ico HTTP/1.1" 404 2957 Not Found: /vendor/phpunit/phpunit/src/Util/Filter.php [28/Dec/2017 05:41:39] "GET /vendor/phpunit/phpunit/src/Util/Filter.php HTTP/1.1" 404 3050 [28/Dec/2017 06:13:04] code 400, message Bad HTTP/0.9 request type ('\x03\x00\x00*%à\x00\x00\x00\x00\x00Cookie:') [28/Dec/2017 06:13:04] "*%àCookie: mstshash=Test" 400 - [28/Dec/2017 06:13:04] code 400, message Bad HTTP/0.9 request type ('\x03\x00\x00*%à\x00\x00\x00\x00\x00Cookie:') [28/Dec/2017 06:13:04] "*%àCookie: mstshash=Test" 400 - -
How to get html content data in suit dashboard widget in django suit
I using python 3 and djnago 1.11. I used Django Suit Dashboard and Display static graph on admin. Its working good but I want to dyanamic graph. I pass html content but its not get in Widget content function. So How to possible it. See, here my widgets.py. class MemberRegistrations(Widget): html_id = 'chart-registrations' template = 'demo/highchart.html' @property def content(self): # this one is a property to avoid "no such table" error at migrate return json.dumps(member_registration_chart()) If, I check self value then display empty {}. I want here self value. See, here my html code. let dataset = {{ widget.content|safe }}; {% for js_code in widget.js_code %} try { if (dataset.{{ js_code }}) { dataset.{{ js_code }} = new Function(dataset.{{ js_code }}); // console.log("dataset:-", dataset) } } catch (err) { console.log(err); } {% endfor %} $('#{{ widget.html_id }}').highcharts(dataset); Here, I passed content in widget but its not passed proper. I have read Django Suit Dashboard , there used same code but not working here. -
Distribute Django App in portable file (windows .exe file for example)
I have Django App and I would like to distribute my App with windows, mac and linux user. I read that Pyinstaller can help me to package my app but I dont know to create portable app which start local server on local user desktop. Does someone can help me? Thanks! -
Django - button url
I get a weird question. I am creating a function to add friend to list, here is my view and url. @login_required(login_url='user:login') def friend_add(request, friend): friendship = FriendShip( from_friend=request.user, to_friend=friend ) friendship.save() return HttpResponseRedirect(request.path) url(r'^add_friend/$', views.friend_add, name="add_friend"), While I call the url in the template: <input type="button" class="btn btn-info" value="Add Friend" onclick="location.href='{% url 'user:add_friend' friend=post.poster %}';"> An exception will happens while loading the webpage: Reverse for 'add_friend' with keyword arguments '{'friend': }' not found. 1 pattern(s) tried: ['users/add_friend/$'] After several attemptions, the webpage can be loaded with the input been removed <input type="button" class="btn btn-info" value="Add Friend" onclick="location.href='{% url 'user:add_friend'%}';"> (This is weird enough because the view is asking for input) However, when I click on the button, another exception happens: friend_add() missing 1 required positional argument: 'friend' I get really confused about this question. Really appreciate for any help! -
Djanog save a model in admin.py
I need to save a parameter(specs which is a dictionary) in Estimate model in django's admin.py. Earlier I used signals but that did not appear to be a wise option. I have below admin.py and here I want to update Estimate's specs field by merging this field with Environment's specs. How can I achieve that? I am still learning Django. I have understood that in the Django admin, when I deal with Estimate model, I get response from Estimate and EstimateAdmin class. At the same time I also have Environment whose foreign key is Estimate and in the Django Admin's Estimate model, Environment is an object. I tried Estimate_specs = Estimate.objects.all() but need to filter the specs on the basis of current estimate and Environment_specs = Environment.objects.all() but again this needs to be filtered with specs on the basis of current estimate. I am not able to figure out how to get this working. class EnvironmentInlineAdmin (admin.TabularInline): model = Environment ... class EstimateAdmin (CommonAdmin): ... admin.site.register(Estimate,EstimateAdmin) class EnvironmentDetailsInlineForm(forms.ModelForm): class Meta: model = EnvironmentDetail fields = ['item_name','qty'] show_change_link = True class AddEnvironmentDetailsInlineForm(forms.ModelForm): ... class EnvironmentDetailsInlineAdmin (admin.TabularInline): ... class AddEnvironmentDetailsInlineAdmin (admin.TabularInline): model = EnvironmentDetail fields = ('item_name','item', 'qty', ) form = AddEnvironmentDetailsInlineForm … -
Django rest framework with djoser token authentication retrieve user first_name
I am using django rest framework djoser authentication. So what i want is when user login, it will return their user token, promptmsg, status, first_name and last_name. djoser: http://djoser.readthedocs.io/en/latest/introduction.html Now i am able to display the token , promptmsg and status but as for the first_name and last_name, i have error trying to do it. serializers class TokenCreateSerializer(serializers.Serializer): password = serializers.CharField( required=False, style={'input_type': 'password'} ) default_error_messages = { 'invalid_credentials': constants.INVALID_CREDENTIALS_ERROR, 'inactive_account': constants.INACTIVE_ACCOUNT_ERROR, } def __init__(self, *args, **kwargs): super(TokenCreateSerializer, self).__init__(*args, **kwargs) self.user = None self.fields[User.USERNAME_FIELD] = serializers.CharField( required=False ) def validate(self, attrs): self.user = authenticate( username=attrs.get(User.USERNAME_FIELD), password=attrs.get('password') ) self._validate_user_exists(self.user) self._validate_user_is_active(self.user) return attrs def _validate_user_exists(self, user): if not user: self.fail('invalid_credentials') def _validate_user_is_active(self, user): if not user.is_active: self.fail('inactive_account') customviews.py class CustomTokenCreateView(cutils.ActionViewMixin, generics.GenericAPIView): """ Use this endpoint to obtain user authentication token. """ serializer_class = TokenCreateSerializer permission_classes = [permissions.AllowAny] def _action(self, serializer): token = utils.login_user(self.request, serializer.user) token_serializer_class = settings.SERIALIZERS.token content = { 'Token': token_serializer_class(token).data["auth_token"], 'promptmsg': 'You have successfully login', 'status': '200', 'first_name': self.request.user.first_name, 'last_name': self.request.user.last_name } return Response( data=content, status=status.HTTP_200_OK, ) This code will give an error : AttributeError at /logintest/ 'AnonymousUser' object has no attribute 'first_name' Is there a way to fix this ? -
SyntaxError when create django project
When I try to create a django project with python3.6, this error raises: Error creating Django application: Error on python side. Exit code: 1, err: Traceback (most recent call last): File "D:\PyCharm 2017.3\helpers\pycharm\_jb_django_project_creator.py", line 12, in <module> management.execute_from_command_line(argv=["django-admin", "startproject", project_name, path]) File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\core\management\__init__.py", line 328, in execute django.setup() File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\__init__.py", line 15, in setup from django.utils.log import configure_logging File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\utils\log.py", line 16, in <module> from django.views.debug import ExceptionReporter, get_exception_reporter_filter File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\views\debug.py", line 9, in <module> from django.core.urlresolvers import Resolver404, resolve File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\core\urlresolvers.py", line 17, in <module> from django.http import Http404 File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\http\__init__.py", line 4, in <module> from django.http.response import ( File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\http\response.py", line 13, in <module> from django.core.serializers.json import DjangoJSONEncoder File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\core\serializers\__init__.py", line 24, in <module> from django.core.serializers.base import SerializerDoesNotExist File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\core\serializers\base.py", line 6, in <module> from django.db import models File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\db\models\__init__.py", line 6, in <module> from django.db.models.query import Q, QuerySet, Prefetch # NOQA File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\db\models\query.py", line 16, in <module> from django.db.models import sql File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\db\models\sql\__init__.py", line 2, in <module> from django.db.models.sql.subqueries import * # NOQA File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\db\models\sql\subqueries.py", line 7, in <module> from django.db.models.query_utils import Q File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\db\models\query_utils.py", line 13, in <module> from django.db.backends import utils File "C:\Users\hasee\AppData\Local\Programs\Python\Python36\lib\site-packages\django-1.8.18-py3.6.egg\django\db\backends\utils.py", line 11, in <module> from …