Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Use one class based view for both List and Retrieve Rest API
I currently have two different class based views for detailing a specific object and for listing all objects: class StatusList(ListAPIView): permission_classes = (IsAuthenticated,) serializer_class = serializers.StatusSerializer def get_queryset(self): queryset = helperfunctions.getObjects(self.request.user, models.Status) return queryset class StatusDetail(RetrieveAPIView): permission_classes = (IsAuthenticated,) serializer_class = serializers.StatusSerializer def get_queryset(self): queryset = helperfunctions.getObjects(self.request.user, models.Status) return queryset Note that helperfunctions.getObjects() simply returns the objects that share the same establishment with the user, so that they can't see statuses that they shouldn't. What I want to know is whether there's an option to use only one class based view for both StatusDetail and StatusList, which would automatically know that when it gets a pk in the get request it returns the appropriate object, and when it doesn't, it should return the whole list of objects. Thanks for any help :) -
django - how to modify bcrypt or how to see its version?
I am building a website for a game server and they use bcrypt, so I do, but their hashes start with $2a$12$ which I know that isn't secure, and my hashes start with bcrypt_sha256$ if using bcrypt with sha256 or bcrypt$ if using only bcrypt. How can I modify bcrypt to start with $2a$12? Also, how can I see the version to check if we have the same version. -
django users table - access from other application (ASP.NET)
I have a working django application with the auth_user table. I want to authenticate users in this table in another C# .NET (Web API) application. What do I need to share to my C# application? I assume I need the SECRET_KEY, and to know how django creates the password hash. -
split list of tuples into a list of strings in python/django
My original list of tuples was list1 and i wanted to split the tuple into a list of strings: list = [Apple,Orange,Grapes] list1= [(u"[u'Apple', u'Orange', u'Grapes']",)] I converted it into list2 list2 = ("[u'Apple', u'Orange', u'Grapes']",)using string_tuple_list = [tuple(map(str,eachTuple)) for eachTuple in list1] but i want to convert this into a list like this: list = [Apple,Orange,Grapes] How can i do this? -
nested for loop to display hierarchical data
I need to display a very simplified Gantt view in a project management app. For this I have a hierarchy of milestones, work-packages and tasks in my database. If I do an oversimplified datastructure of data = [ [ 'milestone', ['segment','segment'], [] ], ['milestone', ['segment'], ['task','task','task'] ], ['milestone', ['segment'], [] ] ] And use a code in my template like below, the display is correct. <table class="table"> <thead> <tr> <th></th> <th></th> </tr> </thead> <tbody> {% for x, y, z in data %} <tr > <td style="color:red;">{{ x }}</td> </tr> {% for yy in y %} <tr> <td style="background-color: lightgrey; padding-left: 20px;">{{ yy }}</td> </tr> {% for zz in z %} <tr> <td style="background-color: grey; padding-left: 40px;">{{ zz }}</td> </tr> {% endfor %} {% endfor %} {% endfor %} </tbody> </table> Now if I want to get realistic data structure with more work-packages(segments) summarising tasks, this solution does not work. See my data structure 'approach' to be more realistic x_new = [ [ 'milestone', ['segment','segment'], [] ], ['milestone', ['segment', ['task','task','task'], 'segment', 'segment', ['task'] ] ], ['milestone', ['segment'], [] ] ] Running this structure, I simply get the task hierarchy be displayed as yet another segment (sound logical). Has anyone a good … -
Should I use the default users model in django 1.11 for my project
Actually, I'm working on a project where I need to save some details like name, username, password, age, gender etc of every user. In that website, any user can login to their account, edit information. So should I use the default users model or create a new model -
django forms: Foreign Key field with 500 options
I have a Django model with Foriegn Key in it. There are almost 500 objects in the ForeignKey model. When i Use ModelForm. it creates a Select element showing 500 objects. I hope this is not a good way to do. Also if I use multi forms this becomes more heavy to load. I am also open for using javascript if necessary -
Creating a "Yelp" like app as Python programmer
I am a hobby data scientist that has mostly been working in Python; scraping data, managing a Postgresql database and writing Jupiter notebook and python data cleaning and machine learning models. I now want to host my own web page where I can offer my data and created insights in a visual way. First objective is to have one page with an interactive map, and then markers that indicate POIs with additional data being offered to user through clicking on a point (through a pop-up bubble but also an area to the side of the map being dynamically updated to show details about selected marker). Basically a Yelp app, with their map feature. What is the best framework or language to do something like this? In my research I have seen django, plotly dash, bookeh, leaflet, react JavaScript etc. What I'm worried about it to pick something to start learning and then 3 months later I realize I don't have flexibility to add a functionality or visualization. I'm in it here to learn, so happy to learn a new language/framework as long as it will help me also down the road to build in more functionality into my website. -
Pinax app.css not found
I am using pinax template for the time.I am following the documentation.I started the project.Did everything mentioned here. The problem is the page is displayed but the css and javascript files are not loaded.The browser console gives error saying Failed to load resource: the server responded with a status of 404 (Not Found) app.css Failed to load resource: the server responded with a status of 404 (Not Found) site.js Am i missing something here? Is there anything else to do which is not there in documentation? -
django shell-plus: how to veiw a model definition from command line
I was using Django Rest Framework and I came across repr() function When I do in the Django shell >> from articles.api.serializers import PostSerializer print(repr(PostSerializer())) PostSerializer(): id = IntegerField(label='ID', read_only=True) publish_date = DateTimeField(format='%Y-%m-%d %H:%M UTC') is_deleted = BooleanField(required=False) title = CharField(max_length=256) intro_image = ImageField(allow_null=True, max_length=100, required=False) slug = SlugField(max_length=50) task_id = CharField(read_only=True) qa_bool = BooleanField(label='Allow Q&A', required=False) Assume i have model Article. I have tried: >> print(repr(Article)) <class 'articles.models.Article'> I want to see all the fields with their properties from shell. Is it possible -
In need of suggestions regarding creating a authorization structure
In my Django project, depending on the groups my users are in and other factors, I need my users to only be able to access some things or the information they get from the database to be limited depending on their access level. there is also a hierarchy on some of the access levels. Now this affects my model managers, views and my templates. Therefore, if I don't define a proper structure, it will be very troublesome in the future. I was wondering if there is a suitable pattern and how I would be able to create a decent Django project for this ( access levels are object level). I would be grateful if somebody could help me. -
Django REST framework add non-model file upload field in model Serializer
I have following model to add video tutorials. class Tutorial(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid4) url=models.CharField(max_length=500) source=models.CharField(max_length=500,choices=SOURCE_TYPE_CHOICES) title=models.CharField(max_length=100) description=models.TextField() thumbnail=models.ImageField() The problem is that the url field may contain a youtube, or vimeo video link or local file link. By default url field is a CHarField but I want to use it as file field in case of local video field. -
GET request with request parameter in Django Resr
I am trying to do GET with a request parameter in Django Rest. views.py :- class ItemView(generics.ListCreateAPIView): queryset = itemlist.objects.all() serializer_class = ItemListSerializer def perform_create(self, serializer): serializer.save() def get_queryset(self): queryset = itemlist.objects.all() get_param = self.request.GET.get('get_param') if get_param: queryset = queryset.filter(item_name=get_param) return queryset urls.py :- urlpatterns = { url(r'^itemlists/$', ItemView.as_view(), name="itemlist") } itemlists/ returns the list of all items. But, I want to return for a particular item, where let's say, item_name = "abcd" URL will look like, itemlists/abcd/ I tried with, urlpatterns = { url(r'^itemlists/(?P<pk>\d+)$', ItemView.as_view(), name="itemlist") }