Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove default filtering by id in django rest framework
How to remove default filtering by id in django rest framework? I want to forbid(or filter by _uid field instead) requests like this http://server/api/employee-list?employee=2. I wrote custom filter and add it to filter_class in my View: class EmployeeFilter(filters.FilterSet): class Meta: model = Employee fields = { 'uid': ['exact', 'in'], 'birth_date': ['day', 'month'], 'first_name': NAME_FILTERS, 'last_name': NAME_FILTERS, 'middle_name': NAME_FILTERS, } But is still able to filter by id. -
Django - UpdateView - Empty select field?
I have an Updateview : class Cotisations_des_adherentsUpdate(UpdateView): model = Cotisations_des_adherents form_class = UpdateCotisations_des_adherentsForm template_name_suffix = '_update' And a model( extract here) : class Cotisations_des_adherents (models.Model): n_reglement = models.AutoField(primary_key=True) cotisation_acquittee = models.FloatField( blank=True , null=True, choices=settings.CHOICE_OUI_NON) frais_de_dossier_acquittes = models.FloatField( blank=True , null=True, choices=settings.CHOICE_OUI_NON) a_jour = models.FloatField( blank=True , null=True, choices=settings.CHOICE_UN_ZERO) the settings value are : CHOICE_OUI_NON = [ (1 , "1-oui" ), (0 , "0-non" )] CHOICE_SEXE = [ (1, "1-Homme" ), (2, "2-Femme" ),] And the form_class inherite from a personnal class: class UpdateCotisations_des_adherentsForm(Cotisations_des_adherentsForm): def __init__(self, *args, **kwargs): super(UpdateCotisations_des_adherentsForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor the super class is (extract here): class Cotisations_des_adherentsForm(ModelForm): error_css_class = 'error' required_css_class = 'required' class Meta: model = Cotisations_des_adherents fields = [ "n_reglement", "cotisation_acquittee", "a_jour", ] def __init__(self, *args, **kwargs): super(Cotisations_des_adherentsForm, self).__init__(*args, **kwargs) My issue is that on the upadte view I don't see the last saved value of the user : cotisation_acquittee frais_de_dossier_acquittes a_jour gives me an empty select html : I understand from the doc that there is something sepecific about the CHOICES option : If the model field has choices set, then the form field’s widget will be set to Select, with choices coming from the model field’s choices. The choices … -
Redirect to success in social auth pipelines
I am using django social auth to enable oauth. I learnt about handling pipelines, and created a partial pipeline for user login. I am saving the data of user(fetched from third party site) directly to UserSocialAuth model from the user defined pipeline. Now, after storing the data I still don't understand how to return success so that the user is redirected to page in login_redirect_url. can anyone help me out thanks this is my pipeline code SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'userauth.social_get_pipeline.get_user') The final pipeline saves the user data successfully. Now what should I return so that remaining part of code is executed successfully and user is redirected to login redirect page -
React limit access to specific users
I'm building an App using react and django as backend. I have JWT authentication set up and working. But I am wondering if it is safe to include menu items and logic of views that will be displayed only to specific users and will include sensitive information. Of course these views will only be visible to the relevant users. My question is if it possible for someone to extract the info from the react build? And if so, what is the best practice to avoid such situation? -
Freeze django model object in time, like a snapshot
Lets say I want to track employees working on projects. Project 2015 - Employee A Employee A now changes his healthcare-provider, address and completes his bachelor degree. Project 2018 - Employee A For Project 2018 the Employee A details are up to date. But if I look back at project 2015 the Employee A details are now newer than the Project itself. For example now it looks like Employee A had a bachelors degree when working at Project 2015, which is incorrect. What I need is like an instance of Employee A frozen in time/time capsule/snapshot/copy when saving him to a Project. While still being able to update the "live" version of the employee. There are other models where I will run into the same problem. It really boggles my mind, because it's so counterintuitive for database-thinking. Is there a right/correct way to handle this. Is there maybe a Django revision? solution? Thank You! -
Django Rest Framework : ForeignKey with Serializer
I've two simples table, with a foreignKey. I want to retreive datas in the table with the foreignkey : CREATE TABLE `firerisk_reminder` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` longtext NOT NULL, PRIMARY KEY (`id`), ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `firerisk_remindertype` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL, `reminder_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`), KEY `firerisk_remindertyp_reminder_id_03340ffc_fk_firerisk_` (`reminder_id`), CONSTRAINT `firerisk_remindertyp_reminder_id_03340ffc_fk_firerisk_` FOREIGN KEY (`reminder_id`) REFERENCES `firerisk_reminder` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; And, so, my model in django : class Reminder(models.Model): name = models.TextField(default='') report = models.OneToOneField(Report, related_name='reminder', on_delete=models.PROTECT) def __str__(self): return self.name class ReminderType(models.Model): name = models.CharField(max_length=45, unique=True) reminder = models.ForeignKey(Reminder,related_name='reminderstype',on_delete=models.PROTECT) In DRF, I'm using serializers like this : class ReminderTypeSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField() class Meta: model = ReminderType fields = ('id', 'name') ordering = ('name',) class ReminderSerializer(serializers.ModelSerializer): remindertypes = ReminderTypeSerializer(read_only=True) id = serializers.IntegerField(read_only=True) name = serializers.CharField() class Meta: model = Reminder ordering = ('name',) fields = ('id', 'name', 'remindertypes') Finally, my ViewSets : class ReminderTypeViewSet(viewsets.ModelViewSet): serializer_class = ReminderTypeSerializer queryset = ReminderType.objects.all().order_by('name') # Authentification ! permission_classes = (IsAuthenticated,) # Only 'get' method http_method_names = ['get'] class ReminderViewSet(viewsets.ModelViewSet): serializer_class = ReminderSerializer queryset = Reminder.objects.all().order_by('name') # Authentification ! permission_classes = (IsAuthenticated,) # … -
django deployment with apache and mod_wsgi
In order to deploy my django project, i've downloaded httpd and mod_wsgi. To configure this module, I've also downloaded apxs and gcc and I've followed this tutorial : https://modwsgi.readthedocs.io/en/develop/user-guides/quick-configuration-guide.html And then I've found in the django documentation : https://docs.djangoproject.com/fr/2.0/howto/deployment/wsgi/modwsgi/ a way to deploy my project. So I actually have this wigs.py : import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ProjetIML.settings") application = get_wsgi_application() And this httpd.conf : WSGIScriptAlias / /home/ninon/ProjetIML/ProjetIML/wsgi.py WSGIPythonPath /home/ninon/ProjetIML <Directory /home/ninon/ProjetIML/ProjetIML> <Files wsgi.py> Require all granted </Files> </Directory> Then I've restart the apache server with "apachectl restart" and when I try to access my site with localhost:80 nothing append. Did I miss something ? I've seen many posts explaining that they have coded files like "django.wsgi" but I haven't found anything about it in the django documentation. I've also tried to add a Virtual host like this : <VirtualHost *:80> WSGIScriptAlias / /home/ninon/ProjetIML/ProjetIML/wsgi.py WSGIPythonPath /home/ninon/ProjetIML <Directory /home/ninon/ProjetIML/ProjetIML> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> But the apache server didn't want to restart. -
how call search index of haystack in django instead of rebuild index
i am updating search index of haystack using rebuild index. but to automate so i am using custom CustomSignalProcessor,it is not working but haystack doc's say send django signal .how send signal to work this search_indexes.py file. i need to send post_save signal to work CustomSignalProcessor? class CustomSignalProcessor(BaseSignalProcessor): def get_connection(self, modelclass): return { 'h_user': ['h_users'], }.get(modelclass.__name__, ['default']) def handle_save(self, sender, instance, **kwargs): backends = self.get_connection(sender) for backend in backends: try: index = self.connections[backend].get_unified_index().get_index(sender) index.update_object(instance, using=backend) except NotHandled: # TODO: Maybe log it or let the exception bubble? pass def handle_delete(self, sender, instance, **kwargs): backends = self.get_connection(sender) for backend in backends: try: index = self.connections[backend].get_unified_index().get_index(sender) index.remove_object(instance, using=backend) except NotHandled: # TODO: Maybe log it or let the exception bubble? pass def setup(self): models.signals.post_save.connect(self.handle_save, sender=h_user) def teardown(self): models.signals.post_save.disconnect(self.handle_save, sender=h_user) and search_indexes.py is class HIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True, template_name='search/indexes/{foldername}/h_users_text.txt') def get_model(self): return h_user def index_queryset(self, using=None): return self.get_model().objects.all() and in settings.py 'h_users': { 'ENGINE': 'elasticstack.backends.ConfigurableElasticSearchEngine', 'URL': 'http://111.11.11.11:9340/', 'INDEX_NAME': 'abcd_users', 'EXCLUDED_INDEXES': [] } } HAYSTACK_SIGNAL_PROCESSOR = 'mysite.search_indexes.CustomSignalProcessor' -
Rails equivalent to django shell
Does rails have an equivalent to django-admin.py shell? Preferably even something that I can run on a remote server? -
error in database saving
I am trying to create a form and save data to database when the submit button is clicked. But the data is not getting saved to database. i dont get any error. I referred to few stackoverflow question and that answers doesnt solve my issue. Could someone help in fixing it? Thanks in advance. model.py from __future__ import unicode_literals from django.db import models class NameForm(models.Model): your_name = models.CharField(max_length=200) views.py from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.views import generic from django.template.response import TemplateResponse from home.models import NameForm from .forms import NameForm class NameView(generic.View): model_class = NameForm initial = {'key': 'value'} template_name = 'home/name.html' def get(self, request, *args, **kwargs): model = self.model_class() return render(request, self.template_name, {'model': NameForm}) def post(self, request, *args, **kwargs): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): return HttpResponseRedirect('thanks/') if form.is_valid(): form.save() else: form = NameForm() return render(request, 'name.html', {'form': form}) urls.py from django.conf.urls import url from . import views app_name = 'home' urlpatterns = [ url(r'^$', views.NameView.as_view(), name='name'), url(r'^your-name/$', views.NameView.as_view(), name='name'), url(r'^your-name/thanks/$', views.NameView.as_view(), name='name'), ] home/name.html <form action="your-name/" method="post"> {% csrf_token %} <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name" value="{{ current_name }}"> <input type="submit" value="OK"> </form> forms.py from … -
How to handle HEAD request gracefully for web crawler and user agents?
Our site is advertised on around 750 blogs. One of the links is making an anonymous HEAD request on our site. The user agent(found in logs) is curl/7.29.0 is actually a robot(maybe a search engine crawlers). After, some study I came to know that user agents often make a HEAD request to decide whether to use cache or make an explicit GET request.[more] 1) One of the best practice advises to not to honor the HEAD request, throw a 405 with allow header. 2) MDN suggests HEAD must never be disabled. I am in a dilemma now, whether to follow the first approach or just send an empty body with status code 200. what are the best practices for a HEAD request in Django? Any help is always welcome. Thank you! -
AWS Elastic Beanstalk 500 error(Django) - Python-urllib/2.7 & static files error
I'm currently deploying the Django & React Web on the Elastic Beanstalk, but I still get the 500 error. Is there any method to get rid of this error? I use postgresql, and I grepped only 500 errors down below. https://github.com/ujin43255252/davidgram Here's my git repo. 172.31.1.112 (14.231.228.185) - - [18/Jul/2018:12:02:48 +0000] "GET / HTTP/1.1" 500 527 "-" "-" 172.31.1.112 (143.248.234.146) - - [18/Jul/2018:12:17:10 +0000] "GET /admin HTTP/1.1" 500 527 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36" 172.31.1.112 (143.248.234.146) - - [18/Jul/2018:12:17:10 +0000] "GET /favicon.ico HTTP/1.1" 500 527 "http://davidgram.ap-northeast-2.elasticbeanstalk.com/admin" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36" 172.31.1.112 (143.248.234.146) - - [18/Jul/2018:12:18:29 +0000] "GET / HTTP/1.1" 500 527 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36" 172.31.1.112 (143.248.234.146) - - [18/Jul/2018:12:18:29 +0000] "GET /favicon.ico HTTP/1.1" 500 527 "http://davidgram.ap-northeast-2.elasticbeanstalk.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36" 172.31.29.137 (31.184.194.109) - - [18/Jul/2018:12:18:33 +0000] "GET / HTTP/1.1" 500 527 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36" 127.0.0.1 (-) - - [18/Jul/2018:12:25:07 +0000] "GET / HTTP/1.1" 500 527 "-" "Python-urllib/2.7" 127.0.0.1 (-) - - [18/Jul/2018:12:25:08 +0000] "GET / HTTP/1.1" … -
how to use DRF in angular5?
i am creating a real time chat application using websocket.. frontend is angular5 and i create websocket service in purepython.. so, i make api of user in drf. then i create model of message : model.py class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') message = models.CharField(max_length=1200) timestamp = models.DateTimeField(auto_now_add=True) # is_read = models.BooleanFeild(default=False) def __str__(self): return self.message class Meta: ordering = ('timestamp',) this is message api This is my websocket.py async def consumer_handler(websocket): global glob_message while True: message = await websocket.recv() await glob_message.put(message) print("this went in glob_message: {}".format(message)) async def producer_handler(websocket): global glob_message while True: message = await glob_message.get() await websocket.send(message) async def handler(websocket, path): producer_task = asyncio.ensure_future(producer_handler(websocket)) consumer_task = asyncio.ensure_future(consumer_handler(websocket)) done, pending = await asyncio.wait( [consumer_task, producer_task], return_when=asyncio.FIRST_COMPLETED, ) for task in pending: task.cancel() if __name__ == '__main__': glob_message = asyncio.Queue() start_server = websockets.serve( handler, '127.0.0.1', 8888) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() In angular side: websocket service export class WebsocketService { private subject: Subject<MessageEvent>; connect(url: string): Subject<MessageEvent> { if (!this.subject) { this.subject = this.create(url); console.log("Successfully connected: " + url); } return this.subject; } private create(url: string): Subject<MessageEvent> { const ws = new WebSocket(url); const observable = Observable.create((obs: Observer<MessageEvent>) => { ws.onmessage = obs.next.bind(obs); ws.onerror = obs.error.bind(obs); ws.onclose … -
Getting a class member name as a string
I have a python class (basically a Django serializer): class UsersSerializer(serializers.Serializer): name = fields.CharField(max_length=40) users = UserSerializerField(many=True) When I use this serializer to serialize a REST request I have to do something like: name = serializer.data.pop("name") In order to get the name field of the serializer's data. This creates a fragile coupling between the class itself and anywhere I use it. Is there a way to do something like: name = serializer.data.pop(serializer.name.__varname__) This way, when refactoring, I will soon figure out there's this place I need to refactor as well. While with using a string, I won't be able to find it. I know I can add a const to the serializer, but I would prefer to have something more elegant. -
Comparing UNIX time with date in Django ORM
I am trying to fetch all records from a table on a particular date. My url.py code is : url(r'^jobs/date/?P<date>.*',userusageDateApiView.as_view()), Here is the code of my view to get all the records from the table. class RunningJobsListApiView(generics.ListAPIView): queryset = LinuxJobTable.objects.annotate(status=Case(When(state=3, then=Value('Completed')),When(state=5, then=Value('Failed')),When(state=1, then=Value('Running')),default=Value('Unknown'),output_field=CharField(),),) serializer_class = JobInfoSerializer Now, I want to filter the jobs for the particular date in url. But In my database date is in UNIX timestamp format(ie.1530773247). How can I compare DateFormat(mm-dd-yyyy) with UNIX timestamp format saved in DB? -
Django Testing: URL mapping to the Class Based View
I'm new to Django testing so trying basic testing codes. But it is showing one error in second test class Tests.py from django.test import TestCase,Client from .views import PostList from django.urls import resolve class SmokeTest2(TestCase): def test_math(self): self.assertEqual(1+1,2) class HomePageTest(TestCase): def test_root_url_resolves_to_home_page_view(self): found = resolve('/') print({'found':found}) self.assertEqual(found.func(), PostList) views.py class PostList(ListView): model = Post template_name = 'home.html' urls.py urlpatterns = [ path('',views.PostList.as_view(),name ='list'), ] When i am printing found its showing the o/p {'found': ResolverMatch(func=blog.views.PostList, args=(), kwargs={}, url_name=list, app_names=[], namespaces=[])} But still I am getting this error (blog_env) PS D:\django\blog_env\mysite> python manage.py test D:\django\blog_env\mysite Creating test database for alias 'default'... System check identified no issues (0 silenced). {'found': ResolverMatch(func=blog.views.PostList, args=(), kwargs={}, url_name=list, app_names=[], namespaces=[])} E. ====================================================================== ERROR: test_root_url_resolves_to_home_page_view (blog.tests.HomePageTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\django\blog_env\mysite\blog\tests.py", line 19, in test_root_url_resolves_to_home_page_view self.assertEqual(found.func(), PostList) TypeError: view() missing 1 required positional argument: 'request' ---------------------------------------------------------------------- Ran 2 tests in 0.069s FAILED (errors=1) Destroying test database for alias 'default'... -
Django update model with original data
I have this modelform, where Invoice_number is being auto generated on save. My problem: when I update any field in this model form a new invoice number is being generated. Is there any way I can update the form and keep the original invoice number unchanged!! class sale(models.Model): name = models.CharField(max_length=30,null=True) contact = models.IntegerField(null=True) email = models.EmailField(max_length=50,null=True) Delivery_Date = models.DateField(null=True) Delivery_time = models.CharField(max_length=80,null=True) service = models.CharField(max_length=20,null=True) Invoice_number = models.CharField(max_length=12,blank=True,unique=True) def save(self, *args, **kwargs): if self.service == 'Furniture': x=randint(99,99999) self.Invoice_number = str('Fur') + str(x) elif self.service == 'Auto': x=randint(99,99999) self.Invoice_number = str('Auto') + str(x) elif self.service == 'Groceries': x=randint(99,99999) self.Invoice_number = str('Gro') + str(x) super(bookings_modelform,self).save() -
Is Twilio prevent from multiple request for phone verification from save number in a day?
I am just trying to integrate Twillow api with my Django for mobile verification. But if anyone trying to verify their account and click on send pin button many times then I want to block him for a day. Is it possible from Twillow api or we have to do that manually? -
Google API Scope Changed
I have a service running on GCP, an app engine that uses Google API. This morning, I've received this "warning" message which threw an 500 error. It has been working fine for the past month and only threw this error today (5 hours prior to this post). Does anyone know why Google returned an additional scope at the oauth2callback? Any additional insight is very much appreciated. Please let me know if you've seen this before or not. I couldn't find it anywhere. Exception Type: Warning at /oauth2callback Exception Value: Scope has changed from "https://www.googleapis.com/auth/userinfo.email" to "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.me". This line threw the error: flow.fetch_token( authorization_response=authorization_response, code=request.session["code"]) The return url is https://my_website.com/oauth2callback?state=SECRET_STATE&scope=https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/plus.me# instead of the usual https://my_website.com/oauth2callback?state=SECRET_STATE&scope=https://www.googleapis.com/auth/userinfo.email# -
mysql finding the sum of subgroup maximums
If I have the following table in MySQL: date type amount 2017-12-01 3 2 2018-01-01 1 100 2018-02-01 1 50 2018-03-01 2 2000 2018-04-01 2 4000 2018-05-01 3 2 2018-06-01 3 1 ...is there a way to find the sum of the amounts corresponding to the latest dates of each type? There are guaranteed to be no duplicate dates for any given type. The answer I'd be looking to get from the data above could broken down like this: The latest date for type 1 is 2018-02-01, where the amount is 50; The latest date for type 2 is 2018-04-01, where the amount is 4000; The latest date for type 3 is 2018-06-01, where the amount is 1; 50 + 4000 + 1 = 4051 Is there a way to arrive directly at 4051 in a single query? This is for a Django project using MySQL if that makes a difference; I wasn't able to find an ORM-related solution either, so figured a raw SQL query might be a better place to start. Thanks! -
What would be the query to allow multiple values for a particular field in elastic search
"hits": [{ "_index": "xyz","_type": "process", "_id": "288","_score":1, "source": "Test"}, {"_index": "abc","_type": "process","_id": "286", "_score":1,"source": "Test1"}, {"_index": "AMC","_type": "process","_id": "287", "_score":1,"source": "Test2"} }] I want to query on this to get results such that source is either Test or Test 1 -
Djnango: Overrroding field name without direct access (django-registration)
I'm using django-registration in my project and wondering whether I can replace a field's name, specifically I want the username field to say "Username/Email" instead of "Username". Is that possible? urls.py: urlpatterns = [ url(r'^accounts/', include('registration.backends.hmac.urls')), url(r'^accounts/register$', RegistrationViewWithContext.as_view(form_class=RegistrationFormUniqueEmail), name='registration_register'), ] Form HTML: <form method="post" class="form-horizontal" action=""> {% csrf_token %} {% if form.non_field_errors %} <div class="non-field-errors"> {% for err in form.non_field_errors %} <p><span class="label label-danger">{{ err }}</span></p> {% endfor %} </div> {% endif %} {% for field in form %} {% if field.errors %} <div class="form-group has-error"> <label class="col-md-4 col-lg-4 col-sm-6 control-label" for="id_{{ field.name }}">{{ field.label }}</label> <div> {{ field|attr:"class:form-control" }} <span class="help-block"> {% for error in field.errors %}{{ error }}{% endfor %} </span> </div> </div> {% else %} <div class="form-group"> <label class="col-md-4 col-lg-2 col-sm-6 control-label" for="id_{{ field.name }}" style="text-align: left">{{ field.label }}</label> <div class="col-md-4 col-lg-4 col-sm-6"> {{ field|attr:"class:form-control" }} {% if field.help_text %} <p class="help-block"><small>{{ field.help_text|safe }}</small></p> {% endif %} </div> </div> {% endif %} {% endfor %} <div class="form-controls offset-lg-2 offset-md-2"> <input type="submit" class="btn btn-primary" value="{% trans 'Log in' %}" /> <input type="hidden" class="btn btn-primary" name="next" value="{{ next }}" /> </div> </form> I guess I can catch the field.name in an if clause in the template but I feel … -
ERROR 1045 (28000): Access denied for user 'root'@'localhost' error happens
When I run python manage.py migrate in my Django app, error happens like Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/management/base.py", line 327, in execute self.check() File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 61, in _run_checks issues = run_checks(tags=[Tags.database]) File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/checks/database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 13, in _check_sql_mode with self.connection.cursor() as cursor: File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/db/backends/base/base.py", line 254, in cursor return self._cursor() File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/db/backends/base/base.py", line 229, in _cursor self.ensure_connection() File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 274, in get_new_connection conn = Database.connect(**conn_params) File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/pymysql/__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/pymysql/connections.py", line 327, in __init__ self.connect() File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/pymysql/connections.py", line 598, in connect self._request_authentication() File "/home/vagrant/.pyenv/versions/3.6.3/lib/python3.6/site-packages/pymysql/connections.py", line 862, in _request_authentication auth_packet = self._process_auth(plugin_name, auth_packet) … -
Getting Django Logger to Create a Log File for Me
I have my logger setup as thus: ...'handlers': { # with debug on, print log messages to the console 'console': { 'level': 'DEBUG', # error message level 'filters': ['require_debug_true'], # choose filter 'class': 'logging.StreamHandler', # iostreams 'formatter': 'verbose' # format of messages }, # with debug on, log messages in dev file 'development_logfile': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.FileHandler', # open and close files 'filename': '/Users/Michael/venvs/wabi/wabi_clean/dev.log'), 'formatter': 'verbose' }, # with debug off, log messages in prod file 'production_logfile': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'logging.handlers.RotatingFileHandler', # have file backups 'filename': os.path.join(BASE_DIR, 'prod.log'), 'maxBytes': 1024*1024*100, # 100MB (max file size) 'backupCount': 5, # number of backup files 'formatter': 'simple' }, 'dba_logfile': { 'level': 'DEBUG', 'filters': ['require_debug_false', 'require_debug_true'], 'class': 'logging.handlers.WatchedFileHandler', # read into more 'filename': os.path.join(BASE_DIR, 'dba.log'), 'formatter': 'simple' },... Where it says 'filename': os.path.join(BASE_DIR, 'prod.log'),, this does not work. I need to put a full path to an already existent file. What am I doing wrong? -
Django - get model fields attributes in views.py
I want to print all fields attribute in my model in html file. But the for loop in my html file seems to be wrong, as it won't print field attributes, but the object itself. How can I modify my views.py or models.py to print the field attribute name on html? I want to print this on html: Api | Name | Region Location | Spud Date | Well Bore | Rig Name | Status well_list.html <thead> <tr> {% for item in well_info %} <th>item</th> {% endfor %} </tr> </thead> views.py from django.shortcuts import render from django.views.generic import View, TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView from . import models class WellInfoListView(ListView): template_name = 'well_list.html' context_object_name = 'well_info' model = models.WellInfo models.py from django.db import models from django.urls import reverse class WellInfo(models.Model): api = models.CharField(max_length=100, primary_key=True) name = models.CharField(max_length=100) region_location = models.CharField(max_length=100) spud_date = models.CharField(max_length=100) well_bore = models.CharField(max_length=100) rig_name = models.CharField(max_length=100) status = models.CharField(max_length=100)