Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(Python Django MySQL) Lost connection to MySQL server during query
I run a Python Djanogo application that once in a day makes a request to the database. while True: today = datetime.date.today() for _ in range(3): print("checking...") # Access objects in the database. events = Event.objects.filter(deadline__gt=last, deadline__lt=today, processed=False) #Sleep once day. sleep(24*60*60) And I get an error I attached the log file from the python app, and I also attached a file from MySQL log. Python app log 0 events resolved. checking... 0 events resolved. checking... Traceback (most recent call last): File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 65, in execute return self.cursor.execute(sql, params) File "C:\Python36\lib\site-packages\django\db\backends\mysql\base.py", line 101, in execute return self.cursor.execute(query, args) File "C:\Python36\lib\site-packages\MySQLdb\cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "C:\Python36\lib\site-packages\MySQLdb\connections.py", line 50, in defaulterrorhandler raise errorvalue File "C:\Python36\lib\site-packages\MySQLdb\cursors.py", line 247, in execute res = self._query(query) File "C:\Python36\lib\site-packages\MySQLdb\cursors.py", line 411, in _query rowcount = self._do_query(q) File "C:\Python36\lib\site-packages\MySQLdb\cursors.py", line 374, in _do_query db.query(q) File "C:\Python36\lib\site-packages\MySQLdb\connections.py", line 277, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python36\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Python36\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python36\lib\site-packages\django\core\management\base.py", line 283, in … -
How to use the rest_framework_tracking.mixins.LoggingMixin in drf-tracking in django
How to use the rest_framework_tracking.mixins.LoggingMixin as stated by Add the rest_framework_tracking.mixins.LoggingMixin to any DRF view to create an instance of APIRequestLog every time the view is called. I have added the class in the views as stated by http://drf-tracking.readthedocs.io/en/latest/#usage. Please let me know on the same. -
django change data type in migration
I had a table with a column typed Polygon, which had dozens of fields. Now I changed the column type to MultiPolygon, but data is still in `polygon' mode. How can I convert all data to new type? There might be a problem that data be so big and we do not want to have them in RAM. tnx -
ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': No module named urls
[INFO] oauth2client.client: Refreshing access_token [ERROR] django.request: Internal Server Error: / get_package_libraries "trying to load '%s': %s" % (entry[1], e) InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': No module named urls This is a python 2.7 project. Django version 1.9 -
Django Forms ModelChoiceField with bootstrap-select
I'm trying to use https://django-bootstrap-select.readthedocs.io with my Django forms and use the 'data-live-search' attribute with my field. So far (to no avail) I have: forms.py: class Someform(forms.ModelForm): f1 = forms.DateField(initial=datetime.date.today, widget=forms.SelectDateWidget()) f2 = forms.ModelChoiceField(Model1.objects.filter(some_filter=0), widget=BootstrapSelect(attrs={'data-live-search':'True'})) class Meta: model = Model2 fields = ('f1', 'f2',) form.html <div class="jumbotron"> <h2>Select from model1</h2> <p></p><form method="post" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <button class="btn btn-primary" type="submit">Submit</button></form> </div> views.py: class FormView(generic.FormView): form_class = forms.SomeForm template_name = 'form.html' -
Many to Many relationships in DJANGO with or without a relation table
I'm new to Django. usually, when having a many to many relationships I would create a separate table to hold the relationship can somebody explain how to do that in Django here is my attempt: a 'Etudiant' can 'Etudier' many 'Modules' a 'Modules' can be 'Etudier' by many 'Etudiant' class Etudiant(models.Model): id_etudiant = models.OneToOneField('Utilisateur', models.DO_NOTHING, db_column='id_Utilisateur', primary_key=True) id_groupe = models.ForeignKey('Groupe', models.DO_NOTHING, db_column='id_Groupe') class Meta: db_table = 'Etudiant' class Module(models.Model): id_module = models.CharField(db_column='id_Module', primary_key=True, max_length=25) titre_module = models.CharField(db_column='titre_Module', max_length=25, blank=True, null=True) uniteenseignement_module = models.CharField(db_column='uniteEnseignement_Module', max_length=25, blank=True, null=True) finsaisie_module = models.IntegerField(db_column='FinSaisie_Module', blank=True, null=True) class Meta: db_table = 'Module' class Etudier(models.Model): id_etudiant = models.ForeignKey('Etudiant', models.DO_NOTHING, db_column='id_etudiant') id_module = models.OneToOneField('Module', models.DO_NOTHING, db_column='id_Module', primary_key=True) class Meta: db_table = 'etudier' unique_together = (('id_module', 'id_etudiant'),) -
Proper way to run a backend project in a VPS
I have a project in Pycharm which is django. its backend is mySQL and uses redis-server and memcached. my VPS is Windows-server 2008. In order to run it in a VPS do i have to move the whole IDE with the project, to VPS and just hit Run in the IDE? It's my first time running a server of my own and it's the only way i can think of. please do correct me if i missed the whole concept. -
Model missing all fields in Django Admin
I have a model with a bunch of fields, and after deploying to production, the django admin shows no fields for that specific model, like at all. I see the top title "Change MODELNAME", and the bottom toolbar with the save buttons. But when i click save, i get a validation error, but still no fields. I get no errors, it's just not showing. The issue occurred after changing something unrelated in the database, and minor changes in the code. But from what i can see, nothing related to the admin. Also the most weird part, it works when running locally using a local database (using postgres in both production and dev env). Django version 1.11.6 -
Change/Update value from an Object via AJAX in Django
I'm using Django Framework and I need some help with POST/GET data via AJAX. I want to change/update is_viewed=True from an Object, when the user click on a specific anchor tag. index.html <ul class="dropdown-menu getNotification"> {% for n in notifications %} <li><a class="dropdown-item" href="/analysis/media/{{ n.n_media_no }}" id="{{ n.n_media_no }}">{{ n.n_media_no }}</a></li> {% endfor %} </ul> <script> $(document).ready(function(){ $('ul.getNotification a').click(function(event) { event.preventDefault(); var media_id = $(this).attr('id'); $.ajax({ //url: window.location.href, type: "POST", // or "get" data: media_id, success: function(data) { alert(data.result); }}); }); }); </script> view.py def home(request): """Renders the home page.""" m_notif = Notification.objects.filter(is_viewed=False) c_notif = Notification.objects.filter(is_viewed=False).count() if request.method == 'POST': if request.is_ajax(): get_value = request.POST.get('media_id') p = MediaNotification.objects.get(pk=get_value) p.is_viewed = 1 p.save() assert isinstance(request, HttpRequest) return render( request, 'app/index.html', { 'c_notif': c_notif, 'm_notif': m_notif, } ) -
Django QuerySet update_or_create creating duplicate entries
Recently I'm facing issues in update_or_create method. Let me give a full explanation first. Model: class TransactionPageVisits(models.Model): transactionid = models.ForeignKey( Transaction, on_delete=models.CASCADE, db_column='transactionid', ) sessionid = models.CharField(max_length=40, db_index=True) ip_address = models.CharField(max_length=39, editable=False) user_agent = models.TextField(null=True, editable=False) page = models.CharField(max_length=100, null=True, db_index=True) method = models.CharField(max_length=20, null=True) url = models.TextField(null=False, editable=False) created_dtm = models.DateTimeField(auto_now_add=True) class Meta(object): ordering = ('created_dtm',) Function: def _tracking(self, request, response, **kwargs): txn_details = kwargs.get('txn_details') data = { 'sessionid': request.session.session_key, 'ip_address': get_ip_address(request), 'user_agent': get_user_agent(request), 'method': request.method, 'url': request.build_absolute_uri(), 'transactionid': txn_details.txn_object, 'page': kwargs.get('page') } # Keep updating/creating tracking data to model obj, created = TransactionPageVisits.objects.update_or_create(**data) Notes: I know I'm not passing any defaults arguments to update_or_create(), as at the time the code was written it was not required (wanted to create a new row only when all the columns as per data is collectively unique). Also _tracking() is in middleware and will be called in each request and response. Everything was going smoothly until today I got following exception: File "trackit.py", line 65, in _tracking obj, created = TransactionPageVisits.objects.update_or_create(**data) File "/usr/local/lib/python2.7/dist-packages/Django-1.10.4-py2.7.egg/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/Django-1.10.4-py2.7.egg/django/db/models/query.py", line 488, in update_or_create obj = self.get(**lookup) File "/usr/local/lib/python2.7/dist-packages/Django-1.10.4-py2.7.egg/django/db/models/query.py", line 389, in get (self.model._meta.object_name, num) MultipleObjectsReturned: get() returned more … -
'Response' object has no attribute 'get'
I am trying perform an auto login by redirecting the user to an external website supplying the authentication information in the header. Tested that it's working in postman. But I am getting a 'Response' object has no attribute 'get' in django when I click on a button which perform this request. I think I am doing this wrongly. What would be the best way to redirect to an external web provided I have the authorization information? Ajax? if req.method == 'POST': url = "https://server.to.reach" headers = { 'Authorization': "Basic YWRtaW46YWRtaW4=", 'Cache-Control': "no-cache", 'Postman-Token': "546de0c9-a4fc-4c0b-8b99-bfbadc9ee7e4", 'Content-Type': "application/x-www-form-urlencoded" } response = requests.request("POST", url, headers=headers) print(response.text) return response -
forms.DateInput default value
I am using a calendar widget using django forms, part of the code- class DateForm(forms.ModelForm): helper.layout = Layout( Div( Field('start', placeholder='date') ) class Meta: model = Date widgets = { 'start': forms.DateInput(attrs={'class':'datepicker'}), } How can I add a default value of todays date to the 'start' variable? I cannot seem to find any default for dateinput. -
python django admin interface, browse records
I want to add two buttons to the record editing window of admin django. One button is to the next record while the other is to the previous. How can I do this? Is there a config parameter to set? -
Django delete() command
I'm building a web app in Django. Their I have a model "DocFile" with a FileField "update". class DocFile(models.Model): name = models.CharField('Bezeichnung', max_length=100) md5sum = models.CharField(max_length=32) upload = models.FileField('Datei', upload_to=media_file_name, storage=MediaFileSystemStorage()) In the followng view I try to delete the database entry (not the file in my media dir) of DocFile where pk=pd. def delete_doc(request, pd, pk): doc = get_object_or_404(DocFile, pk=pd) doc.delete() return redirect('list_docfile', pk=pk) But sadly the delete() command deletes both the database entry and the file in the media dir. I tried to search for a solution but all i got was this: Django delete FileField If Django removed the function that delete() removes the file of the filefield, why does the commadn still removes both in my django application. -
NoReverseMatch in django with kwargs
I'm having trouble getting the {% url %} tag to work with a django view. When visiting the site I get the error: NoReverseMatch at /betalinger/ Reverse for 'confirm' with keyword arguments '{'plan': ''}' not found. 2 pattern(s) tried: ['betalinger/confirm/', 'betalinger/confirm/(?P<plan>.+)/$'] It complains about not finding the url with a keyword argument, but at least one of the urls accepts the plan keyword. urls.py: ... url(regex=r'^confirm/(?P<plan>.+)/$', view=ConfirmFormView.as_view(), name='confirm'), url(regex=r'^confirm/', view=ConfirmFormView.as_view(), name='confirm'), ... And the template making noise: <html> ... <form action="{% url 'payments:confirm' plan=plan.plan %}"> ... </html> -
Getting error when changing sqlite3 to mysql in windows 2012 server iis
i am trying hosting django application to windows server 2012 iis, everything working fine with sqlite3, but when i changed my database to mysql i am getting error. raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb. I changed database settings in django to mysql. Thanks -
Pass username and password with angular 5 http request to django rest api
am integrating django rest api with angular 5. Django rest framework implements it's basic auth and accept username and password. Am able to hit api with postman by providing username and password in Headers menu but when i hit api from angular it retruning 401. I have tried multiple solutions but not getting perfect solution here is what i am trying httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Username': <username>, 'Password': <password> }) }; return this.http.get(url, this.httpOptions) .toPromise() .then(res=>{ return res; }); -
How to reference class instance outside method - Python
I'm writing Django app, I want to create different directory for every different Trip. This code doesn't work (using method): class TripPhoto(models.Model): def __str__(self): return self.trip_id.title trip_id = models.ForeignKey(Trip, on_delete=models.CASCADE) def get_trip_title(self): return self.trip_id.title photo = models.ImageField(upload_to="reservations/" + get_trip_title() + "/") # NEED FIX photo = models.ImageField(upload_to="reservations/" + get_trip_title() + "/") # NEED FIX TypeError: get_trip_title() missing 1 required positional argument: 'self' This code doesn't work too (using attribute): class TripPhoto(models.Model): def __str__(self): return self.trip_id.title trip_id = models.ForeignKey(Trip, on_delete=models.CASCADE) photo = models.ImageField(upload_to="reservations/" + str(trip_id.title) + "/") # NEED FIX photo = models.ImageField(upload_to="reservations/" + str(trip_id.title) + "/") # NEED FIX AttributeError: 'ForeignKey' object has no attribute 'title' I know that I can use self.trip_id.title, because I used it in another part of the code. Is there any way to use self (instance reference?) outside of class method? -
Django rest framework logging different levels on different files
I am working on Django REST framework and I want to have separate files for logging data. I want to have a file for the simple transactions e.g. GET, PUT, POST etc. and one file with the errors that I will collect in case of an error. I have been reading the Django Logging Documentation and I came up with some configurations on how to log the info data. Sample of configurations bellow: settings.py STATIC_URL = '/static/' PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') LOGGING_ROOT = os.path.join(STATIC_ROOT, 'logging') LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': LOGGING_ROOT + "/info.log", }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, } It works as expected sample of data in file: "PUT /upload/dat.txt HTTP/1.1" 204 14 "OPTIONS / HTTP/1.1" 200 10020 "GET / HTTP/1.1" 200 9916 I tried to apply another handler in the settings.py file e.g.: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'fileInfo': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': LOGGING_ROOT + "/info.log", }, 'fileDebug': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': LOGGING_ROOT + "/debbug.log", }, }, 'loggers': { 'django': { 'handlers': ['fileInfo'], 'level': 'INFO', 'propagate': True, }, … -
Authenticate AWS Lambda in Django
Issue: I want to authenticate the response from lambda to Django Summary: My Django app invokes an AWS Lambda with some url, lambda does the processing and a couple of seconds later should return the result to Django. Now, how do I ensure that the response from lambda is valid, and it's not someone trying to call my django endpoint? Setup: Django running on an EC2 machine behind nginx + uwsgi Lambda called from Django using boto3.client('lambda').invoke(...) Lambda code: def handler(event, context): data = event['data'] result = get_my_result(data) requests.post('https://www.example.com/foo/bar', data=json.dumps(result)) I was considering Django REST framework, but it's not like I have a specific user calling the lambda, so I think it doesn't quite suite the purpose. I have never done this kind of 3rd party service authentication in Django, not sure what the most elegant (+secure and efficient) approach would be. Thanks for help! -
Django Foreign Key class not showing
The goal is to have a dashboard show a list of users in your area. The list of users works and it shows the Username. The only issue is I can't get the users images (ideally just have 1st image) to show. There are no error messages currently. Just nothing appearing. models.py class Images(models.Model): image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png') user = models.ForeignKey(User, on_delete=models.CASCADE, null=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True, null=True) birth_date = models.DateField(null=True, blank=True) ... views.py class DashboardView(TemplateView): template_name = 've/cp/dashboard.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(DashboardView, self).dispatch(*args, **kwargs) def get(self, request, pk=None): users = User.objects.exclude(id=request.user.id) try: favorite = Favorite.objects.get(current_user=request.user) favorites = favorite.users.all() except Favorite.DoesNotExist: favorites = None args = { # 'users': users, 'favorites':favorites, 'images': images, } return render(request, self.template_name, args) dashboard.html <div class="col-12"> <h2>People near you</h2> {% for user in users %} <a href="{% url 've:view_profile_with_pk' pk=user.pk %}"> <!--THIS WORKS--> <h4>{{ user.username }}</h4> <p>{{ user.profile.bio }}</p> <!--But not this... why..--> <p>{{ user.images.image.url }}</p> ''' Or this.. However it does work on view_profile page where there is a pk. Seem like it's not finding images for users, as this results in a "No images message on localhost ''' {% if images %} {% … -
Auto Fake Django Migration
I need to auto fake a Django 1.9 migration. Is there a flag that can put in the migration file that will auto fake, rather than having to log onto multiple servers and run. The migrations layout is like this migtarions |-- 0001_initial.py |-- 0002.py |-- 0003.py I know I can do ./manage.py my_app migrate 0002 --fake, but can migration 0002 be auto faked ? and all I need to run is ./manage.py my_app migrate -
What IP do I use to send data from Android to Django Server?
I need to send a JSON from my Mobile Application to a Django server on Ubuntu (which I'm using on Virtualbox). My primary OS is Windows. What IP should I use? Sequence: Android -> Windows -> Ubuntu -> Django Server -
Django - field missing from cleaned data
I am using model form and I'm trying to bypass validation of one particular field. I have ascertained that I need use the clean() method to bypass the field. however when im printing out the cleaned data the assigned_subnets field is not in the dictionary, it is missing output from print: {'site_data': None, 'switches': None, 'hostname': 'STR--RTR-01', 'template': <ConfigTemplates: STR-RTR-01>, 'model': <DeviceModel: Cisco - 4431>, 'install_date': datetime.date(2016, 5, 26), 'ospf_area': None, 'snmp_data': <SNMPData: XXXX>, 'available_subnets': <QuerySet []>} forms.py class DeviceForm(forms.ModelForm): class Meta: model = DeviceData fields = ['site_data', 'switches', 'hostname', 'template', 'model', 'install_date','ospf_area','snmp_data'] def clean(self): super(DeviceForm, self).clean() print(self.cleaned_data) if self.cleaned_data.get('assigned_subnets') in self._errors: del self._errors['assigned_subnets'] return self.cleaned_data def __init__(self, *args, **kwargs): site_id = kwargs.pop('site_id', None) device_id = kwargs.pop('device_id', None) self.is_add = kwargs.pop("is_add", False) super(DeviceForm, self).__init__(*args, **kwargs) devicesubnet = Subnets.objects.filter(devicesubnets__device_id=device_id) sitesubnet = Subnets.objects.filter(sitesubnets__site_id=site_id) common_subnets = list(set(devicesubnet) & set(sitesubnet)) subnet_id_list = [] for s in common_subnets: subnet_id_list.append(s.id) available_subnet_data = sitesubnet.exclude(id__in=subnet_id_list) assigned_choices = [] devicesubnet_data = DeviceSubnets.objects.filter(device_id=device_id) for choice in devicesubnet_data: assigned_choices.append((choice.subnet.id,choice.subnet.subnet)) self.fields['available_subnets'] = forms.ModelMultipleChoiceField( label='Available Subnets', queryset=available_subnet_data, widget = forms.SelectMultiple( attrs = {'class': 'form-control', 'size' : '15'} ) ) self.fields['assigned_subnets'] = forms.MultipleChoiceField( label='Assigned Subnets', choices=assigned_choices, widget = forms.SelectMultiple( attrs = {'class': 'form-control', 'size' : '15'} ) ) self.fields['available_subnets'].required = False self.fields['assigned_subnets'].required = False … -
Django JSON serializer use lowercase for the model
My problem is that Django serializers convert the models names to lowercase. Client side, I get this : { "fields": {"key":"val", "key2":"val2"}, "pk" : 12, "model" : "MyApp.mymodelnametolowercase" } In the documentation is is said : Each such object has two attributes: « pk » and « model », the latter being represented by the name of the app (« sessions ») and the lowercase name of the model (« session ») separated by a dot. This is my code : def list(): lDataList = Book.objects.all() oData = serializers.serialize('json', lDataList) return oData Sorry for not respecting pep8, you'll have to talk to my boss about that though... Anyway, is there a way to tell the serializer not to convert the model name to lowercase ?