Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check django security vulnerabilities and How to fix
** Hello everyone ** Before all i use django 2.1 + python 3.6 I have to admit that django is a framework that makes the life of a developer a lot easier even if it is relative. Now that we've written a django project, done the tests, deployed its web app; Questions: what are the security points that are not particularly covered by django? Can we have a vulnerabilities checklist related to sites written with django ? What are the important security tests for ensured the stability of an app written in django ? Thank for advance... -
Django CBV : post() and form_valid() methods
I would like to use post() and form_valid() methods in order to fill my form, submit data and make some processes with data. My class looks like this : class HomeView(CreateView): """ Render the home page """ template_name = 'freepub/index.html' form_class = CustomerForm def post(self, request, *args, **kwargs): if request.method != 'POST': return HttpResponseRedirect(self.get_success_url()) form = self.form_class(request.POST) email = request.POST['email'] country_id = request.POST['country'] country = Country.objects.get(id=country_id) for checkbox in request.POST.getlist('DocumentChoice'): document = Document.objects.get(id=checkbox) token = self.gen_token(email, document.edqm_id) Download.objects.create(email=email, country=country, pub_id=checkbox, token=token, expiration_date=now + timedelta(minutes=10)) if not form.is_valid(): print('form invalid') continue return HttpResponseRedirect(self.get_success_url()) I would like to add form_valid() method in order to not override my post() method. I tried something like this : def post(self, request, *args, **kwargs): form = self.form_class(request.POST) email = request.POST['email'] country_id = request.POST['country'] country = Country.objects.get(id=country_id) print("I'm in post method") if form.is_valid(): return self.form_valid(form) return HttpResponseRedirect(reverse('freepub-home')) def form_valid(self, form): print("I'm in form_valid method") for checkbox in self.request.POST.getlist('DocumentChoice'): document = Document.objects.get(id=checkbox) token = self.gen_token(self.email, document.edqm_id) Download.objects.create(email=self.email, country=self.country, pub_id=checkbox, token=token, expiration_date=now + timedelta(minutes=10)) self.send_email(self.email, document.upload, document.publication.title, document.edqm_id, token) return super(HomeView, self).form_valid(form) But I don't overcome to make work my class, especially with this issue : 'HomeView' object has no attribute 'email' I think I have a misunderstanding with β¦ -
How to make pageurl return an absolute url
I need Twitter tweet button below every blog post. How do I make {% pageurl %} return an absolute URL of that specific blog post? Thanks -
Sql-server, integring db with Django
I want to connect to the db in sql server using Django. I think I used the correct setup, that is ODBC driver, django-mssql, pyodbc, pyodbc-azure libraries. I can connect to the database, inspect it using instectdb and view the data that already is in db. However, when it comes to adding new field in a createView, I get the following error IntegrityError at /add ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot insert the value NULL into column 'id', table 'test.dbo.Task'; column does not allow nulls. INSERT fails. (515) (SQLExecDirectW); [23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The statement has been terminated. (3621)") I also tried to convert the mssql db to sqlite using SQL converter, but the error I get is similar IntegrityError at /add NOT NULL constraint failed: Task.id It looks like sql server db creates some id fields that cannot work in my case. Even when I compare seemingly the exact same tables in sqlite done from scratch, and sqlite converted from mssql, there are differences (especially this "auto increment" on the left picture). In my model I tried to remove id field completely, use it as IntegerField or AutoField, every time with the same β¦ -
Django app crashes on heroku when minor changes are made
I've got a Django app on heroku that will crashes after a minor change is made (e.g. changing a spelling error in the HTML). The app is deployed already and is in Production mode. The app works fine if I change Debug to True in Settings. What could be the problem and how can I fix this? -
Django Haystack update_index with --remove flag with --age flag gives error
When I am trying the update_index command using django-haystack with --remove flag and --age flag I am getting the following error Failed to query Elasticsearch using '*:*': TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]') without the --age flag it is updating the indexes and removing indexes. I am not sure if it is because of the incompatibility between django-haystack and elastic version 6.2. if it is, are there any workarounds? -
Django: Select one row for each unique value of a field (column)
I have the following model in my Django application; I want to get a queryset of my model with only one row for every unique value of a field (I do not care which row that would be at this point). The problem is I cannot use the distinct function, because I am using annotations in my query. Any idea how this could be achieved? My model class Slot(models.Model): # some other fields here start = models.DateTimeField() Notes This is basically the Django version of this StackOverflow question: SQLAlchemy: Selecting one row for each distinct value of a column -
Differents LOGIN_REDIRECT URL in Django after login
I have many functions in my views (HTML pages). Some of them have @login_required. The problem is that every time after logging in, the redirect is always the same (specified in setting.py). I would like, for example: I write an URL of a page with LOGIN REQUESTED: http://127.0.0.1:8000/aaa/url1 and I get the login, after login I want to be redirected back to http://127.0.0.1:8000/aaa/url1. But this should be with every page with login_required. In this sense, login_redirect_url in settings.py is changeable. How should i do? -
Creating a Django Rest Api to Store Values
I have a python parser who creates two python lists, first one contains some IDs and the second one contains ip:port information which corresponds to those ID's. I need to create a django rest api to send these values and store them. I tried to read django documentation but I still don't know what to do, where to start. Can anyone help me? Thanks in advance. -
Django Rest Framework object level permissions issue while creating an object through POST
My files are as follows: BusinessActionsPermission class BusinessActionsPermission(BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_permission(self, request, view): return True def has_object_permission(self, request, view, obj): business_obj = view.get_business_obj() if request.method in ['GET']: return request.user.has_perm('act_on_business', business_obj) if request.method in ['PUT', 'PATCH', 'DELETE']: return request.user.has_perm('act_on_business', business_obj) return False EmployeeViewSet class EmployeeViewSet(viewsets.ModelViewSet): serializer_class = EmployeeSerializer permission_classes = (permissions.IsAuthenticated, BusinessActionsPermission) def get_business_obj(self, **kwargs): return Business.objects.filter(pk=self.kwargs['business_id']) def get_queryset(self, **kwargs): return Employee.objects.filter(business__id=self.kwargs['business_id']) def create(self, request, *args, **kwargs): business = Business.objects.get(pk=self.kwargs['business_id']) employee = Employee(business=business) serializer = EmployeePOSTSerializer(employee, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) The BusinessActionsPermission is not working while POST method is called to create a new Employee through EmployeeViewSet. A user without act_on_busienss is able to post and create an employee. Django Rest Framework Documentation here says: For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects. which is fine. As the BusinessActionsPermission is working for detailed retrievals with pk. But not working on post which is not a list. Please help. Note: The BusinessActionsPermission above is perfectly working fine for detailed view and doesn't check on list view, which β¦ -
Djnago URL, pass parameters in URL
I want to create url like: /api/foodfeeds/?keywords=BURGER,teste&mood=happy&location=2323,7767.323&price=2 urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^api/foodfeed/(?P<keywords>[0-9.a-z, ]+)/(?P<mood>[0-9.a-z, ]+)/(?P<location>[0-9]+)/(?P<price>[0-9]+)/$', backend_views.FoodfeedList.as_view()), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py class FoodfeedList(APIView): # permission_classes = (permissions.IsAuthenticated,) def get(self,request,keywords,mood,location,price): print(request.GET['keywords']) -
How to pass username in kwargs of Django filter?
In the webapp, to retrieve all the objects from a specific user I am using user pk. But to make url more readable I want to use username. The problem is in the django view, user pk in kwargs giving the correct values, but when I use username it shows error. Here are my codes using 'username' as kwargs, that is returning error, views.py class UserAllQuestionView(generic.ListView): model = Question template_name = 'mechinpy/user_profile_question.html' context_object_name = 'user_all_questions' def get_queryset(self): return Question.objects.filter(user=self.kwargs['username']) urls.py path('m/user/<str:slug>/questions/', views.UserAllQuestionView.as_view(), name='user_profile_question_all'), html <a href="{% url 'mechinpy:user_profile_question_all' user.username %}">All User Questions</a> -
unhandled exception in thread started by ... , in cmd?
Please help me , where is problem here in a picture? enter image description here -
django won't load staticfiles from statifiles_dirs
My style.css is placed in appname/static/appname/. My settings.py has this code: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static/"), ) And in my base.html I load it like this: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'appname/style.css' %}"> But the styles are not loading. If I remove STATICFILES_DIRS and change STATIC_URL = '/static/' to STATIC_URL = '/static/appname/', it works perfectly, but I guess it's not the best practice for the case I'll add any other app to the project later. What I might be doing wrong? -
Django view return vs yield?
That might be quite strange or stupid question, but why can't I use yield instead of return in Django views? Lets say I have simple view: def return_index(request): return render(request, 'index.html') Why next view does not work in Django: def yield_index(request): list_of_templates = ['index.html', 'foo.html', 'bar.html'] for i in range(len(list_of_templates)): time.sleep(5) yield render(request, list_of_templates[i]) Assuming that yield_index view will return different views every 5 seconds. -
Django - Annotate and cast an encrypted TextField to a FloatField to 2 decimal places
I'm using Django pgcrypto fields to encrypt an amount value in a model Invoice as follows: from pgcrypto import fields class Invoice(models.Model): # Some other fields amount_usd = fields.TextPGPSymmetricKeyField(default='') objects = InvoicePGPManager() # Manager used for PGP Fields I'm using aTextPGPSymmetricKeyField because I've to store the value as a float and django-pgcrypto-fields does not have an equivalent for FloatField. Now I need to pass this amount_usd value via an API and I've to restrict the decimals upto two places. I've tried using the following: Invoice.objects.all().values('amount_usd').annotate( amount_to_float=Cast('amount_usd', FloatField()) ) But this gives an error as bytes(encrypted data) cannot be converted to float. I tried using this as well: from django.db.models import Func class Round(Func): function = 'ROUND' template='%(function)s(%(expressions)s, 2)' Invoice.objects.all().annotate(PGPSymmetricKeyAggregate( 'amount_usd')).annotate(amount=Cast( 'amount_usd__decrypted', FloatField())).annotate( amount_final = Round('amount')) I get the following error: django.db.utils.ProgrammingError: function round(double precision, integer) does not exist LINE 1: ...sd, 'ultrasecret')::double precision AS "amount", ROUND(pgp_... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Is there any way to convert the encrypted field to a FloatField of upto 2 decimal places? -
Where is the Django migrations folder?
I must be doing something wrong. Everywhere I see people saying "Look at the migrations folder" but even though I can see migrations there is no folder. Karls-Mac-mini:django_test karl$ tree βββ django_test β βββ __init__.py β βββ __pycache__ β β βββ __init__.cpython-35.pyc β β βββ settings.cpython-35.pyc β β βββ urls.cpython-35.pyc β βββ settings.py β βββ urls.py β βββ wsgi.py βββ manage.py Karls-Mac-mini:django_test karl$ python manage.py showmigrations admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial -
'cx_Oracle.Cursor' object has no attribute 'numbersAsStrings' on Django
I'm struggling with the error on title, I need to install cx_Oracle<6 because of an incompatibility with Django_1.9.X I've tried everything I found in google; setting environment variables, reinstalling instantclient, I don't know what else to do. Running setup.py install for cx-Oracle ... error Complete output from command /Users/mmariscal/sourcetree/save_the_cau/venv1/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/w4/p5qt5g3143n99zm3gy_z79rh0000gp/T/pip-install-2JYYyQ/cx-Oracle/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/w4/p5qt5g3143n99zm3gy_z79rh0000gp/T/pip-record-JvIl3W/install-record.txt --single-version-externally-managed --compile --install-headers /Users/mmariscal/sourcetree/save_the_cau/venv1/include/site/python2.7/cx-Oracle: running install running build running build_ext building 'cx_Oracle' extension creating build creating build/temp.macosx-10.13-intel-2.7-12c creating build/temp.macosx-10.13-intel-2.7-12c/src cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -I/opt/instantclient_12_2 -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c src/cx_Oracle.c -o build/temp.macosx-10.13-intel-2.7-12c/src/cx_Oracle.o -DBUILD_VERSION=5.3 src/cx_Oracle.c:21:10: fatal error: 'oci.h' file not found #include <oci.h> ^~~~~~~ 1 error generated. error: command 'cc' failed with exit status 1 ---------------------------------------- Rolling back uninstall of cx-Oracle Command "/Users/mmariscal/sourcetree/save_the_cau/venv1/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/w4/p5qt5g3143n99zm3gy_z79rh0000gp/T/pip-install-2JYYyQ/cx-Oracle/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/w4/p5qt5g3143n99zm3gy_z79rh0000gp/T/pip-record-JvIl3W/install-record.txt --single-version-externally-managed --compile --install-headers /Users/mmariscal/sourcetree/save_the_cau/venv1/include/site/python2.7/cx-Oracle" failed with error code 1 in /private/var/folders/w4/p5qt5g3143n99zm3gy_z79rh0000gp/T/pip-install-2JYYyQ/cx-Oracle/ Thanks -
How do i pass a forms "text" input into another variable that is in views.py
In my Django project, I have to take the input from forms and pass it as an argument for a function that is in views.py. How do I do it? -
Django 2.1 Testcase Client getting unauthorized after logging in
I'm trying to upgrade my application from Django 1.11 to Django 2.1 and while I have been able to sort out most migrating issues, the API tests stopped working in the migration. After checking them, I see that I am getting a response with status code 401 (Unauthorized). I tried manually from the shell and this is what I get: In [46]: from django.test import Client In [47]: c = Client() In [48]: user = User.objects.create(username='foobar') In [49]: user.set_password('foobar') In [50]: user.save() In [51]: c.login(username=user.username, password='foobar') Out[51]: True In [52]: c.get('/me/') Unauthorized: /me/ Out[52]: <Response status_code=401, "application/json"> In [53]: c.get('/me/').content Unauthorized: /me/ Out[53]: b'{"detail":"Authentication credentials were not provided."}' So, apparently, for some reason, my Client is logging in but it is not authorized, although in Django 1.11 it was working fine without any changes. The API and the App is still working fine. Any ideas? -
How to dissalow nginx serving static files when subdomain isn't recognized by django?
I have a configuration with statics file served by nginx at location /static and django (though gunicorn) on / location. My app in multitenant and i use subdomain for identifying tenant. Nginx servername is: server_name ~^(.*.)?my-domain.loc$; My django is sending 404 error when accessing / on a subdomain that don't exist. I want to not give response to (ever django or static) when django response is 404 for a subdomain. any idea ? -
How to print continues readings from arduino serial to a django template?
So I have a project in which I have made a django website and connected an arduino with my system. I have a water flow sensor which gives continues readings of flowrate, volume etc (even when no water is flowing). Now I want to Display the current Volume (which is obtained from the arduino) on a webpage. My Arduino Code is something like this: So flowRate = Liters/Minute β¦ Perfect! Now we just need to write it to Serial so we can actually see the data: int flowPin = 2; //This is the input pin on the Arduino double flowRate; //This is the value we intend to calculate. volatile int count; //This integer needs to be set as volatile to ensure it updates correctly during the interrupt process. void setup() { // put your setup code here, to run once: pinMode(flowPin, INPUT); //Sets the pin as an input attachInterrupt(0, Flow, RISING); //Configures interrupt 0 (pin 2 on the Arduino Uno) to run the function "Flow" Serial.begin(9600); //Start Serial } void loop() { // put your main code here, to run repeatedly: count = 0; // Reset the counter so we start counting from 0 again interrupts(); //Enables interrupts on the β¦ -
TypeError when python manage.py migrate
I got a problem when 'python manage.py migrate' after startrpoject and config my database, is there any step i miss? the database create two blank tables: migrations, content_type centos7.5 python 3.4 django 1.11.15 oracle 18c > [root@localhost djtest]# python manage.py makemigrations No changes detected [root@localhost djtest]# python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/usr/python3/lib/python3.4/site-packages/django/core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/usr/python3/lib/python3.4/site-packages/django/core/management/init.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/python3/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/python3/lib/python3.4/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/python3/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/python3/lib/python3.4/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/python3/lib/python3.4/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/python3/lib/python3.4/site-packages/django/db/migrations/executor.py", line 250, in apply_migration self.recorder.record_applied(migration.app_label, migration.name) File "/usr/python3/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 73, in record_applied self.migration_qs.create(app=app, name=name) File "/usr/python3/lib/python3.4/site-packages/django/db/models/query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "/usr/python3/lib/python3.4/site-packages/django/db/models/base.py", line 808, in save force_update=force_update, update_fields=update_fields) File "/usr/python3/lib/python3.4/site-packages/django/db/models/base.py", line 838, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/python3/lib/python3.4/site-packages/django/db/models/base.py", line 924, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/usr/python3/lib/python3.4/site-packages/django/db/models/base.py", line 963, β¦ -
Complex django annotation
I have the following models:- class Group(models.Model): name = models.CharField(max_length=200) class Game(models.Model): group = models.ForeignKey(Group, related_name='games') date = models.DateField() players = models.ManyToManyField( Player, through='GameMembership', related_name='games' ) class GameMembership(models.Model): game = models.ForeignKey(Game, related_name='memberships') player = models.ForeignKey(Player, related_name='memberships') selected = models.BooleanField(default=False) injured = models.BooleanField(default=False) class Player(models.Model): group = models.ForeignKey('groups.Group', related_name='players') user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='players') I want to annotate all of the players in the group with a score which is calculated as follows:- For the last 10 games for which a player wasn't injured, score 5 if they were selected. I can do this using Sum/Case/When if I ignore the "wasn't injured" clause, by using a manager method on Player which looks something like this:- def with_availability_scores(self, group): for_games = group.games.reverse()[:10] return self.annotate( availability_score=Sum(Case( When( memberships__selected=True, memberships__game__in=for_games, then=5) default=0, output_field=IntegerField())) ) But the addition of the "injured" clause means that I can't use that for_games variable like that to begin with. I suspect it can be done using Subquery and OuterRef but I can't quite figure out the exact syntax I need. Any ideas? -
Django creating Comment System with Ajax
I want to create a comment system for my page. The system should work without refreshing page.I am very new at Ajax and I probably missing somethings but I don't know what. When I click "comment" button, the page shows something like; my codes: view.py def post_detail(request, pk, ): post = get_object_or_404(Post, pk=pk) form = CommentForm(request.POST or None) if form.is_valid(): name = request.POST['name'] content = request.POST['content'] comment = Comment() comment.name = name comment.content= content return JsonResponse(model_to_dict(comment), safe=False) context = { 'post': post, 'form': form, } return render(request, 'blog/post_detail.html', context) models.py class Comment(models.Model): name = models.CharField(max_length=200, verbose_name='name') content = models.TextField(verbose_name='comment') created_date = models.DateTimeField(auto_now_add=True) comment.html {% load crispy_forms_tags %} <hr> <form method="POST" style="width: 50%; margin-left: 20px" id="comment_form"> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn btn-info" value="Yorum Ekle" style="margin-left: 20px"> </form> post_detail.html <div id="comment"> <h2>Yorum Ekle:</h2> {% include 'blog/comment.html' %} <hr> {% for comment in post.comments.all %} <h4>{{ comment.name }} | <small>{{ comment.created_date|timesince }} ΓΆnce</small> </h4> <p>{{ comment.content|linebreaks }}</p> {% endfor %} </div> <hr> <hr> <script type="text/javascript" src="{% static 'js/jquery-1.11.1.min.js' %}"></script> <script type="text/javascript"> $(document).ready(function () { $("#comment|form").submit(function (e) { e.preventDefault(); var url = "/post/12"; $.ajax({ type: 'POST', url: url, data: $("#comment_form").serializeArray(), success: function (data) { console.log('SUCCESS'); } }); }); }); </script> β¦