Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a django form, but instead of giving a file, give a folder/directory
I want to write a django form to upload a set of files to the database. However I don't want to do this with separate files - I want to have 'search button' and give the folder path, taking info from each file to upload to different models. Is there a way to handle this with an inbuilt django form (like using file = forms.FileField()) -
Python list: list index out of range
I am not so much familiar with python and got this code from a friend of mine and need some community help here to solve this issue.I'm getting "list index out of range" error from the following line. days = list(zip(Leave_type.objects.filter(type=leavetype).values_list('max_days', flat=True))[0]) Note: I have already execute migrations and setup my database already. def timeoffapply(request): if not request.session.get('id', None): return render(request, 'login.html') else: stdate = request.POST['startDate'] enddate = request.POST['endDate'] leavetype = request.POST['leaveType'] days = list(zip(Leave_type.objects.filter(type=leavetype).values_list('max_days', flat=True))[0]) d1 = datetime.strptime(stdate, "%Y-%m-%d") d2 = datetime.strptime(enddate, "%Y-%m-%d") d3 = abs((d2 - d1).days)+1 empid = (request.session['id'])[0] countdays = Leave.objects.filter(Emp_id = empid,type=leavetype).aggregate(Sum('days')) if countdays['days__sum'] == None: finaday = (days[0] - 0) else: finaday=(days[0] - countdays['days__sum']) if enddate>=stdate: if finaday >= d3: getleaveid = list(zip(Leave_type.objects.filter(type=leavetype).values_list('id', flat=True))[0]) split_lt_id = ("".join(str(e) for e in getleaveid)) empid = (request.session['id'])[0] get_emp_name = list(zip(Employee.objects.filter(id=empid).values_list('name', flat=True))[0]) get_emp_name = ("".join(str(e) for e in get_emp_name)) empid = (request.session['id'])[0] leave_id = Leave.objects.all().count() test = Leave(id=(leave_id + 1), name=get_emp_name, type=leavetype, start_date=stdate, end_date=enddate, days=d3, status="pending") test.Emp_id_id = empid test.leave_type_id_id = split_lt_id test.save() return HttpResponseRedirect('/') else: qs = Leave.objects.all().filter(Emp_id=(request.session['id'])[0]) context = { "qs": qs, "error": "true", "msg": "You are allowed to have holidays for " + str(finaday) + " days in " +str(leavetype) } return render(request, 'timeoff.html', context) -
python Django admin module occurs 404 error
I'm learning Django recently, I'm writing code according to official documentation.However, when I try to use the admin module, the bug occurs.Here is my project structure: structure and code in django_demo/urls.py: from django.urls import include, path from django.contrib import admin urlpatterns = [ path('poll/', include('poll.urls')), path('admin/', admin.site.urls), ] poll/urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>', views.detail, name="detail"), path('<int:question_id>/results/', views.results, name="results"), path('<int:question_id>/vote/', views.vote, name="vote"), ] settings.py: INSTALLED_APPS = [ 'poll.apps.PollConfig', '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', ] -
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration ... is applied before its dependency
I get this exception: myproject@aptguettler:~$ manage.py migrate Traceback (most recent call last): File "/home/myproject/src/djangotools/djangotools/bin/manage.py", line 32, in <module> main() File "/home/myproject/src/djangotools/djangotools/bin/manage.py", line 29, in main execute_from_command_line() File "/home/myproject/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/myproject/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/myproject/local/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/myproject/local/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/myproject/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 86, in handle executor.loader.check_consistent_history(connection) File "/home/myproject/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 292, in check_consistent_history connection.alias, django.db.migrations.exceptions.InconsistentMigrationHistory: Migration myapp.0029_bar is applied before its dependency myapp.0005_foo_squashed_0028_dynamic_year on database 'default'. My migrations: name ------------------------------------------- 0001_initial 0002_... 0003_... 0004_... 0005_foo 0006_... 0007_... ... 0028_dynamic_year 0029_bar 0030_... What could be the reason? -
django rest cant get session varible in get request
i have the following class for user's peyment progress when the request is POST , im setting amount in session like this request.session['amount'] = amount and when the request is GET i should get the session but session is empety and the if statment if 'amount' in request.session: is alwasy false ... how can i fix this?? class PaidApiView(APIView): MMERCHANT_ID = '??????????' # Required ZARINPAL_WEBSERVICE = 'https://www.zarinpal.com/pg/services/WebGate/wsdl' # Required amount = None # Required description = None # Required products = None email = 'user@userurl.ir' # Optional mobile = '09123456789' # Optional CallbackURL = 'http://127.0.0.1:8000/store/paid/' def post(self, request, *args, **kwargs): amount = request.data['amount'] products = request.data['products'] productstitle = request.data['productstitle'] productsTitlestr = ''.join(productstitle) self.amount = amount self.products = products self.description = productsTitlestr request.session['amount'] = amount client = Client(self.ZARINPAL_WEBSERVICE) result = client.service.PaymentRequest(self.MMERCHANT_ID, self.amount, self.description, self.email, self.mobile, self.CallbackURL) if result.Status == 100: return Response('https://www.zarinpal.com/pg/StartPay/' + result.Authority) else: return Response('Error') def get(self, request): if 'amount' in request.session: self.amount = request.session['amount'] client = Client(self.ZARINPAL_WEBSERVICE) if request.GET.get('Status') == 'OK': result = client.service.PaymentVerification(self.MMERCHANT_ID, request.GET['Authority'], self.amount) if result.Status == 100: del request.session['amount'] return Response('Transaction success. RefID: ' + str(result.RefID)) elif result.Status == 101: del request.session['amount'] return Response('Transaction submitted : ' + str(result.Status)) else: del request.session['amount'] return Response('Transaction failed. … -
How do I use a datetime object in a Django template filter?
I have a specific set of date formats that I want to set based on language and am hoping to do this with a Django template filter. This is what I currently have: @register.filter def date_with_lang(date_item, language): supported_languages={ 'en': '%M. %d, %Y', 'fi': '%M. %d, %Y'} if language in supported_languages: format_type = supported_languages[ĺanguage] else: #default to english if we can't find it. format_type = supported_languages['en'] return datetime.strftime(format_type) But with this design I get a string for the datatype. Do I need to translate the string version of the date to a datetime first? Sound silly. Perhaps another solution would be to put a method for the printout in the model. What's your take? How is this best done? -
How many connections a Python Django App opens by default?
I have a couple of services which query objects from the database. Event.objects.filter Connection.objects.filter and other methods to retrieve different objects from MySQL database. I come from JVM background, and I know that to setup a JDBC connection, you need a connector. A programmer can open a connection, query the database and close the connection. A programmer also can use Hibernate, which handles connection according to the configuration. Also it is possible to use pooled connections, so connections are not closed and removed, but stored in the pool untill they are needed. However, I checked my teams Python Django code, and I did not find how db connection is configured. The only thing I got is which does not configure connections. # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases try: import database_password DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "mydb", 'USER': 'user', 'PASSWORD': database_password.password, 'HOST': '10.138.67.149', 'PORT': '3306' } } -
(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?