Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send axios put request with jwt token in reactjs
I have tried to put details to server but getting 403 error below is my code. export const updateAppTypeData = (appData) => async dispatch => { const token = localStorage.getItem('token') const response = await axios({ method : 'put', url: ('http://localhost:8000/api/posts/appType/'+appData.id+'/'), data: appData, headers: {'Content-Type': 'application/json', 'Authorization': 'Token '+token}, json: true }).then(function (response) { console.log(response); }); //dispatch({ type : FETCH_APP_TYPE , payload: response.data }); }; Any help will be a big plus. Thanks. -
Django version 2.1 Django-admin.py startproject only creates manage.py
I'm using anaconda on Windows 10 with python version 3.6.5. These are the commands that I ran: pip install virtualenvwrapper.win mkvirtualenv firstBlog workon firstBlog pip install Django Django-admin.py startproject firstBlog cd firstBlog dir and this is the output I get: 08/22/2018 02:48 PM <DIR> . 08/22/2018 02:48 PM <DIR> .. 08/22/2018 02:48 PM <DIR> firstBlog 08/22/2018 02:48 PM 556 manage.py 1 File(s) 556 bytes 3 Dir(s) 137,288,876,032 bytes free Why did startproject not make init.py, urls.py and settings.py? I should add that I'm trying to make a website that someone can draw numbers with their mouse onto a 28x28 grid and then have a neural network recognize the number they drew on the website. It's a passion project of mine. -
How can I add CSS file in django
django 2.1 Im using django 2.1 and i cant find my css folder in django -
Elastic search querying
I'm having some issues with my elastic search querying. I have the following fields, patientid, patientfirstname, patientmidname, and patientlastname. I want to be able to enter in either one of those 4 fields and get matching results returned. So far my query works only if I use a patientid. If i type something like harry (firstname) or middle/last name it doesn't query it. Individual term querying works for each of them. q = Q({"bool": { "should": [ {"term":{"patientid":text}}, {"wildcard":{"patientlastname":"*"+text+"*"}}, {"wildcard":{"patientfirstname":"*"+text+"*"}}, {"wildcard":{"patientmidname":"*"+text+"*"}} ]}}) r = Search().query(q)[0:10000] -
How database data can be updated by id - Django
Hi guys im new in django and I want to update my database. I have my form and my model that create correctly all the data in my database. When this was created the performance field gets default value 0 and the created field gets the creation date. Everything up to this moment is perfect. I have this model and this view: models.py from django.contrib.auth.models import User class Model(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) performance = models.FloatField(default=0) created = models.DateTimeField(auto_now_add=True, null=True) class Meta: ordering = ['-created'] views.py def form_x(request): user = request.user form = XForm(request.POST or None) if form.is_valid(): performance = form_data.get('performance') obj = Model.objects.create(user=user, performance=performance,) return redirect('form') else: form = TForm() return render(request, 'funciones/btc.html', {'form':form}) My question: How can i update the performance field searching by id, AUTOMATICALLY after 1 min once the POST request has been sent? i dont know whats better if use a function update view or a Class Update View What you recommend? Thank you so much! -
How to Save a Screenshot of a Page in Django and Store it in Model's ImageField
I have the model: class Post(models.Model): image = models.ImageField(upload_to='post_images/', blank=True, null=True) title = models.CharField(max_length=200) content = models.TextField() When somebody creates a post, I want to take a screenshot of the post (for social media sharing) and save the image in the post's image field. How can I do this using Selenium? Thanks for any help, Jack -
Default list of dicts using JSONField in Django
Django 2.0, Django-Rest-Framework 3.8, Python 3.6 I'm using a Postgres database and am trying to set up the following as a default value for the JSONField: from django.db import models from django.contrib.postgres.fields import JSONField class TrainerProfile(models.Model): """data required to pull up trainer profile""" specific_workouts = JSONField(default=[{"specific": "standard session", "price": 100.00, "units": 1, "hours_per_unit": 1}, {"specific": "standard session", "price": 250.00, "units": 3, "hours_per_unit": 1}, {"specific": "standard session", "price": 300.00, "units": 5, "hours_per_unit": 1}]) def __str__(self): return str(self.specific_workouts) From the Django docs, it reads: If you give the field a default, ensure it’s a callable such as dict (for an empty default) or a callable that returns a dict (such as a function). Incorrectly using default={} creates a mutable default that is shared between all instances of JSONField. I want to provide a list containing dicts as the default. I'm allowed to post a list of dicts through raw data or the browsable api in Django Rest Framework, but I need to know how to set this up by default. I want it to post this as the default: "specific_workouts": [ { "price": 100.0, "units": 1, "specific": "standard session", "hours_per_unit": 1 }, { "price": 250.0, "units": 3, "specific": "standard session", "hours_per_unit": 1 … -
How to block a specific user agent in Apache
I'm configuring my Django app to email me errors (exceptions). Normally no problem - but my email is hosted on Office 365, and it seems that Microsoft is automatically scanning and loading URLs within emails. The result is that it hits the URL in my Django app, and causes another error... and another email. End result: a charming little mail loop which sends me 50+ messages within a few seconds. I found entries like this in my apache logs: 157.55.39.163 - - [22/Aug/2018:17:30:05 +0000] "GET /testerror HTTP/1.1" 500 5808 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534+ (KHTML, like Gecko) BingPreview/1.0b" I want to block access to the user agent (containing "BingPreview"), so I can prevent this loop. I put this into my virtualhost: SetEnvIf User-Agent "^.*BingPreview.*$" bad_user <Directory /path/top/my/app/> <Files wsgi.py> Require not env bad_user </Files> </Directory> But when I reload apache, I get the error negative Require directive has no effect in <RequireAny> directive. -
How to override get_swagger_view to enable django-rest-swagger to display all endpoints?
By default django-rest-swagger displays my views which do not require authentication(JWT Auth in this case). I tried to override the default get_swagger_view shortcut by adding IsAuthenticated in the permission classes to include the views which require authentication also. But as soon as I visit the rendered docs this time, I get No operations defined in spec! How do I display both the views which do and do not require authentication. -
When revoking Google credentials, should one delete the saved credentials?
I'm adapting the Flask example at https://developers.google.com/api-client-library/python/auth/web-app to a Django app. I have a question about the revoke view, which in Flask is: @app.route('/revoke') def revoke(): if 'credentials' not in flask.session: return ('You need to <a href="/authorize">authorize</a> before ' + 'testing the code to revoke credentials.') credentials = google.oauth2.credentials.Credentials( **flask.session['credentials']) revoke = requests.post('https://accounts.google.com/o/oauth2/revoke', params={'token': credentials.token}, headers = {'content-type': 'application/x-www-form-urlencoded'}) status_code = getattr(revoke, 'status_code') if status_code == 200: return('Credentials successfully revoked.' + print_index_table()) else: return('An error occurred.' + print_index_table()) Note that in the Flask example, a dictionary with the information needed to pass to the google.oauth2.credentials.Credentials constructor is saved in the session, but it is recommended in the code sample to store it persistently in a real application. What I'm wondering is: after revoking the token, should we in this example not do del flask.session['credentials'] to prevent the /authorize view from encountering revoked credentials the next time? The reason I'm asking this is because in my Django application I'm getting a RefreshError: RefreshError at /create-meeting ('invalid_grant: Token has been expired or revoked.', '{\n "error": "invalid_grant",\n "error_description": "Token has been expired or revoked."\n}') Here is my sample code: import datetime import requests from django.utils import timezone from django.conf import settings from django.shortcuts … -
Sum of child nodes in accounting hierarchy in django/python
How do you create a sum of child nodes into a a parent node for multiple levels in an accounting hierarchy with Python/Django? I currently have an app which displays the sum of individual accounts, but these values are not added to parent level accounts. The app has the following models: from django.db import models class accounts(models.Model): account_nr = models.IntegerField(null=True) account_name = models.CharField(max_length=100) account_parent_nr = models.IntegerField(null=True) class transactions(models.Model): transaction_id = models.CharField(max_length=100) account_ID = models.ForeignKey(accounts, on_delete=models.CASCADE) debit_value = models.DecimalField(max_digits=10, decimal_places=2) credit_value = models.DecimalField(max_digits=10, decimal_places=2) Some sample data is: account_nr account_name account_parent_nr 1000 current assets null 1001 cash 1000 1002 bank 1000 1010 debtors 1000 1011 debtor 1 1010 1012 debtor 2 1010 3000 stock null 3010 category 1 3000 3011 product a 3010 3012 product b 3010 ... 0010 equity null 0011 owner x 0010 0012 owner y 0010 Sample data for transactions would be: transaction_id account_id debit_value credit_value 1 1001 100 0 1 0011 0 100 2 1002 100 0 2 0011 0 100 3 1011 100 0 3 0011 0 100 4 1012 100 0 4 0011 0 100 5 3011 50 0 5 3012 50 0 5 0012 0 100 The following view is used: from django.shortcuts import … -
QR code in pdf from html page with django
I have a problem writing a generated QRcode into a PDF file using Django. The PDF is generated but the QRcode is not added, i tried adding another images and works but not with the QRcode. This is my template: {% extends "pdf/base.html" %} {% load humanize %} {% load utils %} {% load qr_code %} {% block report_header %}QR del auto{% endblock %} {% block customer_header %} <p class="clean-padding"><strong>Placa:</strong> {{car.plate}}</p> <p class="clean-padding"><strong>Fecha y hora:</strong> {{car.created_at}}</p> {% endblock %} {% block content %} <img src='{% qr_url_from_text "Hello World!" size=8 version=10 image_format="png" %}' alt="Hello World!"> {% endblock %} -
How can I send multiple key values in one for?
I was wondering how I send multiple key values to the back end So from my submit my dictionary data = request.POST.copy() looks like this: Dictionary on breakpoint And I have a for loop that gets the keys and send them with their key values but it only accepts one key value: data = {key: data.get(key) for key in data.keys() if data.get(key)} How could I make this for loop accept more than one key value? -
Django iframe load denied by xframe options even after view is set to @xframe_options_exempt
I have a django app where I want to embed one embed view as an iframe on any site. thought I had this configured correctly because I'm setting the view as @xframe_options_exempt, but I'm still getting an x-frame options err in Chrome and Firefox. Chrome: Refused to display 'https://foo.com/embed/...' in a frame because it set 'X-Frame-Options' to 'deny'. Firefox: Load denied by X-Frame-Options: 'https://foo.com/embed/...' does not allow framing views.py from django.shortcuts import render, get_object_or_404, redirect from django.views.decorators.clickjacking import xframe_options_exempt @xframe_options_exempt def embed(request, bar_slug, slug): embed_object = get_object_or_404(foo, slug=slug) if embed_object.bar.slug != bar_slug: raise Http404 embed_url = '{}{}'.format('https://foo.com/embed', embed_object.get_absolute_url()) context = { 'embed_object': embed_object, 'embed_url': embed_url, 'embed_url_encode': urlquote_plus(embed_url), } return render(request, 'causes/embed.html', context) settings.py MIDDLEWARE_CLASSES = [ 'djangosecure.middleware.SecurityMiddleware', 'project.utils.middleware.SiteMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'project.utils.middleware.HoneypotMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I assume djangosecure.middleware.SecurityMiddleware is enforcing 'X-Frame-Options' over @xframe_options_exempt. I would prefer to address this with a view-specific solution and not set X_FRAME_OPTIONS = 'ALLOW'. thanks -
Clearing sessions on django server startup
I would like to invalidate all ongoing sessions when the django server starts up. Is there a simple way to do this? Thanks. -
How to make a computed fieldset's legend in django admin?
I have a model: class SolutionsPage(Page, SingletonModel): systems_title = models.CharField(max_length=200) ... And a corresponding ModelAdmin: @admin.register(SolutionsPage) class SolutionsPageAdmin(SummernoteModelAdmin): fieldsets = ( (<I want systems_title to be the legend of fieldset>, { 'fields': ('systems_title', ) }) ) How to make systems_title to be the fieldset's legend? -
Understanding which database to use as the 'NAME' when connecting to an AWS RDS MySQL database using Django
I created a new AWS mysql database instance with RDS, and I'm trying to connect to it from my Django app on my machine. Django requires the default database connection to be formatted like so in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'innodb', 'USER': 'username', 'PASSWORD': 'password', 'HOST': '--------.us-west-2.rds.amazonaws.com', 'PORT': '####' } } My question concerns the 'NAME' parameter. I connected to the AWS instance from my command line using the provided endpoint and port number in the RDS console and checked to see what databases were there. This is a brand new database instance I created with RDS, and there were 5 databases. $ mysql -h ---------.us-west-2.rds.amazonaws.com -P #### -u username -p Enter password: mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | innodb | | mysql | | performance_schema | | sys | +--------------------+ The only one of these databases that was empty was the one called innodb. At first I thought the NAME parameter was supposed to be 'mysql', since that is the name of the database server I'm using. But when I used 'mysql' as the name and ran python manage.py migrate I got an error saying django.db.migrations.exceptions.MigrationSchemaMissing: Unable to … -
Drop down list for custom field in Django admin
In my admin, I have a custom form field that is not part of the model. I need to implement drop-down list for it. I've tried django-admin-list-filter-dropdown, but it seems that it isn't working with custom fields. Also heard about grappelli, but failed to find solution for my case in its documentation. So I have following code in my admin.py: class ContentManagerFilter(SimpleListFilter): title = 'Content manager' parameter_name = 'content_manager' def lookups(self, request, model_admin): users = User.objects.filter( logentry__content_type_id=7, logentry__action_flag=1).distinct() return [(user.username, ' '.join((user.username, str(LogEntry.objects.filter( user__username=user.username, content_type_id=7, action_flag=1).count())))) for user in users.order_by('username')] def queryset(self, request, queryset): if self.value(): return queryset.filter( id__in=list(LogEntry.objects.filter( user_id=User.objects.get( username=self.value())).values_list('object_id', flat=True))) @admin.register(Page) class LandingPageAdmin(admin.ModelAdmin): list_display = ('slug', 'is_active', 'updated_at') list_filter = (ContentManagerFilter, 'category') I will be very grateful for any ideas. -
python/django/geodjango project on Windows or Linux (without Apache)?
I am new to django and trying to use it to build a website for a school project, but I am wondering if I should develop on my local Windows machine or Linux server? I've researched to try and see pros and cons of each, but it's still not clear to me with what I am trying to do which would be the easiest route. I am hesitant to start until I can see what potential problems I may run into in the future, but I don't know enough to foresee these issues. I know this question has similarly been asked before, but this was five years ago and I am wondering if there have been recent developments that would cause this answer to change. A couple things about my project: I am mainly trying to host a platform to interact with a database. The website will be used to return queries from the database, and hopefully (though not required) visualize some of the data in a map. Currently this database is in shapefile format and has ~1.5 million polygonal objects with 15+ attributes. I've read that this can be converted from shapefile to database/postGIS in django. The website does … -
Unable install requirements.txt
After cloning a Django application, I went to install the virtual environment in terminal. I entered the folder and typed: pip install -r requirements.txt but got the error: -bash: pip: command not found -
Deploy django on windows server 2016
How to deploy my app django with anaconda envirenment in windows server 2016 with iis Thank you -
reactjs not able to perform put with axios
I am not able to perform put request in reactjs, redux and python django. I have also gone through the one of the answer for the same in stackoverflow but no luck Below is the action code when user click on button. export const updateAppTypeData = (appData) => async dispatch => { const token = localStorage.getItem('token') const response = await axios({ method : 'put', url: 'http://localhost:8000/api/posts/appType/'+appData.id+'/', data: appData }).then(function (response) { console.log(response); }); //dispatch({ type : FETCH_APP_TYPE , payload: response.data }); }; Below is the Server side code for url urlpatterns = [ url(r'^$',ApkStatusView.as_view()), url(r'^(?P<id>\d+)/$',ApkStatusAPIDetailView.as_view()), url(r'^appType/$',AppTypeStatusView.as_view()), url(r'^appType/(?P<id>\d+)/$',AppTypeStatusAPIDetailView.as_view()), ] Server side code for view class AppTypeStatusAPIDetailView( mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.RetrieveAPIView): lookup_field = 'id' permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = AppTypeSeriializer queryset = Apptype.objects.all() def put(self,request, *args, **kwargs): return self.update(request, *args, **kwargs) def patch(self,request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self,request, *args, **kwargs): return self.destroy(request, *args, **kwargs) Thanks for the help. -
How to add a custom field in django model form?
I'm trying to add a readonly field in a form. The model Folder is registered in admin site. The FolderAdminForm define this custom field: statistics. There isn't 'statistcs' field in the Folder model. I just want to put some readonly data on the form. This data is defined in the template. But I get a error whenever the user doesn't have edit permission. If the user only have the view permission,this error is raised: AttributeError: Unable to lookup 'statistics' on Folder or FolderAdmin class CustomWidget(forms.Textarea): template_name = 'widget.html' class FolderAdminForm(forms.ModelForm): class Meta: model = Folder fields = ('field1', 'field2', 'field3',) statistics = forms.Field( widget=CustomWidget, label='Estatísticas', help_text='Estatísticas da pasta', ) -
How to set Django model date field default value to future date?
I'm trying to set the default value for a Date field to a future date with respect to today. However, it gives me the following warning when I set is as below. return_date = models.DateField(default=(timezone.now() + timedelta(days=1))) booking.Booking.return_date: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now` Same warning with the following code. return_date = models.DateField(default=(date.today() + timedelta(days=1))) What is the correct way to do this? Thanks. -
Django migration adding a UUIDField with a default
I have a simple Django migration where I've added a UUIDField to the Invoice model as follows. Model field: uuid = models.UUIDField( _('Unique invoice ID'), default=uuid.uuid4, editable=False, ) Generated migration: migrations.AddField( model_name='invoice', name='uuid', field=models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='Unique invoice ID'), ), When I run this migration, every invoice gets the same UUID value as the others, almost as if the uuid.uuid4 function is called once and then that value is reused for all objects. I use PostgreSQL and Django 1.11. What am I doing wrong here?