Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to detect window pop up created by user in python django?
Is there any way you can configure your python code to catch if the user is using pop up message such as alert("hello world")? I couldn't find any dedicated window alert method in python and really struggling to experiment my XSS game. This vulnerable example takes everything from the user. #views.py from django.shortcuts import render from django.http import HttpResponse def test(request): if request.method == 'GET': context = {'comments' : ''} else: context = {'comments' : request.POST['comments'] } response = render(request,'attack1.html',context) #disabling xss protection header response['X-XSS-Protection'] = 0 return response #html <!DOCTYPE html> <html> <head> </head> <body> <form action="" method="POST"> {% csrf_token %} Say something: <br> <textarea rows="3" cols="60" name='comments'>{{comments}}</textarea> <br> <input type="submit" value="comments"> </form> <br> Your comment: <b>{{comments|safe}}</b> </body> </html> -
Getting a A {% csrf_token %} was used in a template, but the context did not provide the value. Error in DJango
When I execute it from this point: Firswt I log in to the Application (the authentication system is created using the one from DJango) Eventually, I will land on a HTML template that runs the code below {% csrf_token %} The code above calls he following: @login_required def homepage(request): app_logonid = request.user.username return render(request, 'mainadmin/base.html', { 'firstname': app_logonid }, ) When following this sequence of steps, I get the following warning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. Why am I getting this and how can I resolve it? TIA -
Django Rest Framework: Issue using OrderingFilter and django-filter simultaneously
I have a viewset which needs to have both flexible ordering by parameter and filtering by parameter for a custom list() over-ride. I am able to get ordering to work as well as filtering on various parameters via django-filter, but I cannot get them both to function simultaneously. Here is my simplified views.py code that works for ordering the results: class AssetViewSet(viewsets.GenericViewSet, AssetPaginationMixin,): queryset = Asset.objects.all() pagination_class = AssetPagination serializer_class = serializers.AssetSerializer filter_backends = (OrderingFilter, ) ordering_fields = ('id', 'session_id') filter_class = AssetFilterSet def list(self, request): assets = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(assets, many=True) return Response(serializer.data) And here is the code that works for filtering: class AssetViewSet(viewsets.GenericViewSet, AssetPaginationMixin,): queryset = Asset.objects.all() pagination_class = AssetPagination serializer_class = serializers.AssetSerializer filter_backends = (OrderingFilter, ) ordering_fields = ('id', 'session_id') filter_class = AssetFilterSet def list(self, request): assets = AssetFilterSet(request.query_params) serializer = self.get_serializer(assets, many=True) return Response(serializer.data) And finally, my filters.py code: class AssetFilterSet(django_filters.FilterSet): project_id = django_filters.NumberFilter() submitted = django_filters.TypedChoiceFilter(choices=BOOLEAN_CHOICES, coerce=strtobool) class Meta: model = Asset fields = ['project', 'submitted'] The only difference is the first line in list(). For some reason, it seems like the AssetFilterSet needs to be applied directly within list() in order to take effect and is otherwise bypassed if I use self.filter_queryset in … -
django testing passing request.user to foreignKey field, "Event.creator" must be a "User" instance
I am trying to write test for a view that creates an event model object. The event model contains a foreignKey field that references auth user as the creator of the model object. In the test I tried logging in the user which I assumed would set the request.user to the user logged in. The view that is being tested references request.user when creating the event the works fine when triggered normally through ajax but when I run the test I keep getting the error below. Also I have tried creating the user within the test function instead of referencing the user created at "class.setupTestData()", same error. error ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x108ae9cc0>>": "Event.creator" must be a "User" instance. model class Event(models.Model): name = models.CharField(max_length=200) event_type = models.CharField(max_length=200, null=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, null=True) attendees = models.ManyToManyField(User, related_name='attendees') start_date = models.DateField(null=True) start_time = models.TimeField(null=True) end_date = models.DateField(null=True) end_time = models.TimeField(null=True) location = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True) description = models.TextField() def __str__(self): return self.name view def createEvent(request): # dec vars event_title = str(request.POST['event-title']).title() event_type = str(request.POST['event-type']) event_location = str(request.POST['event-location']) event_description = str(request.POST['event-description']) event_start_date = str(request.POST['event-start-date']) event_start_time = str(request.POST['event-start-time']) event_end_date = str(request.POST['event-end-date']) event_end_time = str(request.POST['event-end-time']) creator = request.user … -
django 1.10, custom auth backend, is it ok to use just 1 custom backends?
I read it(Log in user using either email address or username in Django) and use this backend custom backend: from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class EmailOrUsernameModelBackend(ModelBackend): def authenticate(self, username=None, password=None): if '@' in username: kwargs = {'email': username} else: kwargs = {'username': username} try: user = User.objects.get(**kwargs) if user.check_password(password): return user except User.DoesNotExist: return None and settings.py: AUTHENTICATION_BACKENDS=[ 'logintest.custombackend.EmailOrUsernameModelBackend', ] Although it works well but I wonder whether I should use backend like this: AUTHENTICATION_BACKENDS=[ 'logintest.custombackend.EmailOrUsernameModelBackend', 'django.contrib.auth.backends.ModelBackend' ] Do I use it both backends? or It's ok for just one custom backend? -
Django can not import a local python package when runserver
I'm developing a simple django app, but I encounter an import issue. Here is my folder structure: django_intuitive_pagination/ ├── example │ ├── config │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── items │ │ ├── admin.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations/ │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ └── manage.py ├── intuitive_pagination │ ├── __init__.py │ ├── mixins.py │ ├── paginator.py │ ├── templates/ │ ├── templatetags/ │ └── views.py ├── runtests.py └── tests/ I add intuitive_pagination in example.config.settings.py as a django app. Add in example.items.views.py, I also import a class from intuitive_pagination.views.py. However, when I run python manage.py command, django complaint ImportError: No module named 'intuitive_pagination' I am sure the top level of the project did in python path >>> sys.path [..., '/home/light/Workspace/PycharmProjects/DjangoProjects/django_intuitive_pagination'] full stack: Traceback (most recent call last): File "/home/light/.virtualenvs/intuitive_pagination/lib/python3.5/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/light/.virtualenvs/intuitive_pagination/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/home/light/.virtualenvs/intuitive_pagination/lib/python3.5/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/home/light/.virtualenvs/intuitive_pagination/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/light/.virtualenvs/intuitive_pagination/lib/python3.5/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/light/.virtualenvs/intuitive_pagination/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File … -
django orm not interacting with database (the title name is not showing up in queryset)
im entirely new to programming and im not all that good with every computer science term, anyway,inside this django tutortial im learning to create a blogsite, right now we are at the point where we are using the django ORM to interact witht the database, i was following every step and i hit a wall at queryset, where the item name isnt showing up, and this was after i def __str__(self): return self.title the output that i get when i type Narticle.objects.all() is queryset Narticle:Narticle object(1) instead of <queryset [<Narticle: 'hello world']> -
Trying to upload a file to SharePoint with API/django
I'm newer to django but I built app that allows users to login with their Office365 account via django-allauth and I want to be able to upload documents to SharePoint Online automatically through the app. I found this guide... https://www.coderedcorp.com/blog/uploading-files-to-sharepoint-with-django-and-pyth/ where the author does the same thing. The difference is he uses a different authentication backend I think instead of allauth. It sounds like he uses the OneDrive API. I've never used APIs before so this will definitely be a learning process. I'm trying to understand how he did this.. It sounds like he first uses python-social-auth to authenticate via Office365/AzureAD then makes the api call with def handle_file_upload: So to me it sounds like since I already have users authenticated with Office365/AzureAD and I have the correct permissions allocated to the app in dev.microsoft as well as the correct scope in my settings file, I can just write a method similar to his that makes the api call? Something like... def handle_file_upload(file_to_upload): # Getting the authenticated user credentials from allauth_office365 social = request.user.social_auth.get(provider='office365') #Im using a different authentication backend/provider than the author did in the article access_token = social.extra_data['access_token'] # build our header for the api call headers = … -
Django Admin: search by date with url parameters
I have a model defined like this in Django 1.11: class MyModel(Models.Model): ... some fields... created_date = models.DateTimeField() #YYYY-MM-DD h:m:s Now I want be able to search im MyModel by date in my template. To do that I extended change_list and all was right. My problem is: what I have to do for retrive object(s) with a specific created_date? Suppose you want the element(s) created at 2017-12-13. If I go to the shell I achieve this by: MyModel.objects.filter(created_date__date='2017-12-13') And all work ok, and I get my data. But why the __date operator do not work in URL? If I put the __date operator in url, like this: 127.0.0.1:8000/admin/.../?created_date__date=2017-12-13 I get an error: /?e=1 So I tested another way by using __lte and __gte operators. Like before you want object created at 2017-12-13, so I combined __lte and __gte operators in this way: MyModel.objects.filter(created_date__gte='2017-12-13', created_date__lte='2017-12-13') But in this case I get an empty query set. Also in this way: 127.0.0.1:8000/admin/.../?created_date__gte=2017-12-13&created_date__lte=2017-12-13 So, my questions: Why __lte and __gte operators work as URL parameters and __date no (I get /?e=1)? I have tested with other dates and nothing ghange. How can I get a specific created_date object(s)? -
Django Reverse for 'authentication' with arguments '()' and keyword arguments '{}' not found
I'm working on a Django(1.10) project and I'm getting this error, it happens to me suddenly as it's working fine before. Reverse for 'authentication' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Here's my HTML template slsDeployment.html: {% include 'base.html' %} {% load staticfiles %} {% load bootstrap3 %} <title> Serverless Deployment</title> <link rel="stylesheet" href="{% static 'css/materialize.css' %}"> <style> .nav-link { color: white; } a.nav-link.waves-light.active { color: black; background-color: white; } .tooltipped{ width: 24%; } #inline_index, #inline_package{ background: url(http://i.imgur.com/2cOaJ.png); background-attachment: local; background-repeat: no-repeat; padding-left: 35px; padding-top: 10px; border-color: #ccc; } </style> <body> <div class="container-fluid"> <div class="row total-content"> {% include 'nav.html' %} <div class="col-md-9 content"> <div class="world-map" style="width: 100%; margin-left:2%"> <h3> Serverless Deployment :</h3> </div> <div class="col-lg-12"> {% if messages %} <div class="container" style="margin-top: 10%;padding-bottom: 0;background-color: #2F5671;margin-left: 2%;font-size:1.2em;color:ghostwhite; border-radius: 20px"> {% for message in messages %} <div class="alert alert-{{ message.tag }}" role="alert"> <strong>{% if message.tag == success %} Well done! {% else %} Oh snap! </strong>{% endif %} {{ message }} </div> {% endfor %} </div> {% endif %} <br/> <form method="POST" id="slsForm" name="slsForm" class="form-horizontal" action="" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group" style="margin-top: 10%;"> <br/><h5> Your selected project is: <b>{{ project }}</b></h5><br> <label hidden for="project">Project </label> … -
executing django model query?
In django model query, i want to know the sequential execution of it. Consider a query Blog.objects.get(name='palm'). In this where the Blog is defined, is that same as class blog in models.py? What is objects i can't find anything related to this in source files of django. If Blog is a class, then what is the type of objects? -
How to realise a dynamic AND combined query on a ManyToMany relation in Django
I have two simple models. Let's say Tags and Posts. They look like this (simplified): class Tag(models.Model): name = models.CharField(max_length=255, blank=False, unique=True) class Post(models.Model): title = models.CharField(max_length=255, blank=False, default='') tags = models.ManyToManyField(Tag) So, each tags can be assigned to n posts and vice versa. I'm trying to get a list of either all posts where ANY of the given tags are assigned, or where ALL of the given tags are assigned. So basically I want an OR or an AND combination. The OR is easy enough. In my view I do queryset = Post.objects.filter(tags__in=tags) But I can't figure out how to do that for and AND combination. I either get nothing or the same as with OR. I tried a lot of different things, but nothing worked in my scenario, where I have a dynamic list of tags to filter by. How can this be done? -
try to install mysqlclient inside virturalenv but failed
(my_project) [yw@yanbox my_project]$ pip install mysqlclient File "/tmp/pip-build-zza957yo/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/tmp/pip-build-zza957yo/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found any ideas how to fix this problem? -
docker healthcheck shows not found in django
I added health check to my docker file: HEALTHCHECK --interval=1m --timeout=5s --retries=2 --start-period=10s \ CMD wget -qO- http://localhost:8070/healthcheck || exit 1 In my project main urls.py file I added entry: url(r'^healthcheck/', lambda r: HttpResponse()) The project is activated and deployed, so I can understand the healthcheck is valid, however - I keep getting: 2017-12-17 13:25:27,891 WARNING base 51 140551932685128 Not Found: /healthcheck written to the logs (once a minute). The log entry is added also when I run the wget from inside the server. Is it an issue with the healthcheck syntax, the django entry set up or the wget in docker? Please assist. thanks. -
iOS not playing html5 videos
I build a lan video server using Django. And I use the video tag to play videos so no extra players are needed to be installed. The videos play quite well in other platforms like windows or android. But it doesn’t work on my iPhone no matter the size or format of the video file. Moreover, when I use wireshark to analyze the data packages. I found out that the data is transferred correctly at the beginning, but the client closed the socket connection immediately . It’s quite bizarre. Can anyone help me figure out what’s going wrong here.Any suggestions will be helpful, Ps: I edited it on my phone, so sorry for the terrible format. -
Materialize Collapsible feature not working on Django
I'm learning django and currently using materialize as a framework in order to keep things simple. My problem is that the collapsible feature creates the headers but doesn't expand when clicked. this is the ul snippet <ul class="collapsible" data-collapsible="accordion"> <li class="collapsible-header"><i class="fas fa-book"></i> &nbsp; Ingegneria <div class="collapsible-body"> <p>Al momento (e nei prossimi anni probabilmente) frequento </br>ingegneria dell'automazione</br> a Bologna. Studiare prende la maggior parte del mio tempo e nel caso non fossi rintracciabile probabilmente mi trovo nell'acquario: l'aula studio principale della sede di via Terracini. </p> </div> </li> <li class="collapsible-header"><i class="fas fa-microphone"></i> &nbsp; Stand-Up Comedy <div class="collapsible-body"> <p>Ora vi starete dicendo "questo ragazzo non sa neanche cosa sia una vita sociale". </br> Ed in parte è vero, ma un giovedì ogni due settimane esco dalla mia grotta e insieme agli altri comici di </br>stand-up italia</br> partecipo all'open mic presso il Brewdog bar.</p> </div> </li> </ul> and this is my head snippet {% load staticfiles %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Filippo Guarda</title> <!-- css --> <link rel="stylesheet" href="{% static 'webapp/css/materialize.css' %}" type="text/css" media="screen" /> <script defer src="https://use.fontawesome.com/releases/v5.0.1/js/all.js"></script> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- javascript --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="{% static 'webapp/js/materialize.js' %}"></script> I tried with adding … -
Django Rest Framework: Are there any Date based archive views like Django
I want to get a Json with Month based archives. I saw https://docs.djangoproject.com/en/2.0/ref/class-based-views/generic-date-based/#montharchiveview for Django. Is there any thing similar in rest framework -
django-rest-swagger double slash
I'm having trouble with django-rest-swagger. I did everything (or I think I did) like in swagger documentation, but when I try to test API via "Try it out!" button, it sends request like this, with double slashes "GET /api//activity/ HTTP/1.1" 404 8388 my_app/urls.py router = routers.DefaultRouter() router.register(r'activity', ActivityViewSet) router.register(r'diary', DiaryViewSet) router.register(r'discipline', DisciplineViewSet) router.register(r'ingredient', IngredientViewSet) router.register(r'product', ProductViewSet) router.register(r'mealtype', MealTypeViewSet) router.register(r'meal', MealViewSet) urlpatterns = [ path('docs/', get_swagger_view(title='API')), ] urlpatterns += router.urls urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('diet_app.urls')) ] How it looks at swagger site What could be the problem? -
How to generate download link
I'm triying to create a link to download file which has been uploaded. models.py class Comentario (models.Model): archivo = models.FileField(upload_to='media', null=True, blank=True) settings.py MEDIA_ROOT=os.path.join(BASE_DIR, 'media') MEDIA_URL='/media/' template.html <a href="{{ MEDIA_URL }} {{detail.archivo.url}}" download>Descargar</a> When I click the download link it does not download the .jpg saved in 'media' folder. Is the path incorrectly specified? Thank you for your answer -
What is the right way to read the content of .docx which come from frontend as ArrayBuffer?
I am using react-dropzone to upload files. Here is onDrop function: onDrop(file) { const reader = new FileReader(); reader.onload = () =>{ const fileAsArrayBuffer = reader.result; this.props.uploadFile(fileAsArrayBuffer); }; reader.readAsArrayBuffer(file[0]); } Here is my action: export const uploadFile = file => async dispatch => { const res = await axios.post('api/upload_file', file); dispatch({type: FETCH_OVERVIEW, payload: res.data.overview}) }; On the back-end I am using Django Rest Framework.I do post request on api which contains ArrayBuffer. I tried to use python's docx library. Also I tried xml library as in Array was xml tags but attempts was unsuccessful. How to do it right? -
How to prefetch a @property with a Django queryset?
I would like to prefetch a model property to a queryset in Django. Is there a way do that ? Here are the three models: class Place(models.Model): name = models.CharField(max_length=200, blank=True) @property def bestpicurl(self): try: return self.placebestpic.picture.file.url except: return None class PlaceBestPic(models.Model): place = models.OneToOneField(Place) picture = models.ForeignKey(Picture, on_delete=models.CASCADE) class Picture(models.Model): file = ImageField(max_length=500, upload_to="/images/") I would need something like: qs = Place.objects.all().select_related('bestpicurl') Any clue how to do that ? Thanks! -
How to implement OAuth2 Implicit Grant with Django REST framework
I've been searching the web for a decent tutorial on how to implement OAuth2 implicit grant authorization with Django Rest Framework but couldn't find any resources. Only tutorials for Authorization Code Grant and other types are available or concerns pure Django (not DRF). How to do it step-by-step? Do I need to reinvent the wheel and code it from scratch? -
Using variable value to call/create model object in django [duplicate]
This question already has an answer here: Django: Get model from string? 8 answers Is there a way to use the variable value, to create a model? Here is what i mean : myModel = 'modelNum1' myModel.Objects.create() -
signup url is not shown when using login form in other template
I am using django allauth for user registration part. I need to use login template also in checkout template if user is anonymous. For that I wrapped the login form template inside a content block so I can reuse only the form element in other template. This way I could see the signup url only in the account/login page but not in checkout page Here is what I have done account/login.html (allauth account) {% extends "account/base.html" %} {% load i18n %} {% load account%} {% block head_title %}{% trans "Sign In" %}{% endblock %} {% block content %} {% include 'account/snippets/login_form.html' %} {% endblock %} login_form.html {% load i18n %} <div class="container-fluid"> <div class="row"> <div class="col-sm-12 col-md-6 col-md-offset-3"> <h1>{% trans "Sign In" %}</h1> <p>{% blocktrans %}If you have not created an account yet, then please <a href="{{ signup_url }}">sign up</a> first.{% endblocktrans %} /* href is empty in checkout page */ </p> <form class="login" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} {{ form }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <a class="btn btn-warning secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a> <button class="btn btn-primary" type="submit">{% trans "Sign In" … -
OR filter on MultipleChoices with django-filter
I have a form field with choices like [1, 2, 3, 4+], that 4+ means greater than equal and multiple choices can be selected. I want to do the filter using django-filter. I could do the filter for [1, 2, 3], but I don't know how to or it with gte=4. both the following work for filtering [1,2,3]: class NumberInFilter(django_filters.BaseInFilter, django_filters.NumberFilter): pass class PlanFilter(FilterSet): obj = django_filters.NumberInFilter(name='object', lookup_expr='in') class Meta: model = Plan fields= ['object',] or choices= ( (1,1), (2,2), (3,3), ) class PlanFilter(FilterSet): obj = django_filters.MultipleChoiceFilter(name='object', choices=choices) ... So how can I filter the multiple choices with a gte=4 field?