Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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") } -
how to use manage.py inexplicitely
so when I'm im in my root directory (where manage.py lives), if I do manage.py runserver it says command not found. I have to do ~/<project_name>/manage.py runserver for it to work. Why is this? -
Forbidden from accessing Django server
What I have done so far: Acquired a Django stack from Bitnami via AWS, it is up and running. I developed a very simple Django app called frontPage on my local Windows machine, its views.py is shown below from django.http import HttpResponse def index(request): return HttpResponse("Hey.") its urls.py file is shown below from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index) ] in mysite container folder, its urls.py file is shown below: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^frontPage/', include('frontPage.urls')), url(r'^admin/', admin.site.urls), ] in mysite container folder, I added app frontPage to its settings.py file as shown below: INSTALLED_APPS = [ 'frontPage', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] the overall structure of my own Django project is: When I executed py manage.py runserver on my local Windows machine, I could access localhost:8000/frontPage with a browser and it showed "Hey". I connected to this Bitnami Django stack via WinSCP and copied my entire "mysite" folder over to under /opt/bitnami/apps/django/django_projects/. From /opt/bitnami/apps/django/django_projects/mysite, I executed python3 manage.py runserver 0.0.0.0:8000, the server is up and running But when I tried to access bitnamiIP:8000/frontPage from my Windows machine, I got a timeout message. What … -
Struggling with a unit-test
ERROR: test_dont_remember_cc (p38.tests.test_stripepayment.StripePaymentTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/infinity/.virtualenvs/p38-1/src/p38/p38/tests/test_stripepayment.py", line 70, in test_dont_remember_cc self.pay(mock_cc(brand='Visa', extra={'amount': '1.00', 'cc_hash': 'new', 'remember_cc': False})) File "/home/infinity/.virtualenvs/p38-1/src/p38/p38/tests/test_stripepayment.py", line 47, in pay self.client.post(reverse('zoneclient-payment'), cc, follow=follow) File "/home/infinity/.virtualenvs/p38-1/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 551, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/home/infinity/.virtualenvs/p38-1/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 468, in _reverse_with_prefix (lookup_view_s, args, kwargs, len(patterns), patterns)) NoReverseMatch: Reverse for 'zoneclient-payment' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P<clientcode>[0-9]{9})/payment/$'] Here is the unit test def test_dont_remember_cc(self): self.signin() self.pay(mock_cc(brand='Visa', extra={'amount': '1.00', 'cc_hash': 'new', 'remember_cc': False})) rs = self.client.post( reverse('zoneclient-payment', kwargs={'clientcode': 000111222}), {'amount': '1.00', 'quickform': True} ) m = re.search('(var cards =.*)(card_\w+)"(.*)(Visa|Mastercard)', rs.content) self.assertEqual(m, None) self.assertEqual(200, rs.status_code) and in the urls.py file is I have the following # Online payment url(r'^(?P<clientcode>[0-9]{9})/payment/$', csrf_exempt(login_required(OnlinePaymentView.as_view())), name='zoneclient-payment'), It is unclear how to fix that test. Any help? IMPORTANT Be aware I modify that project inside .virtualenv/p38-1/src/p38. I can't apply migrations directly inside p38, because is an app, not a django project. In clear, p38 is a lib inside a virtual environment. I am working on a real django project which use that. ┌─╼ [~/.virtualenvs/p38-1/src/p38/p38] └╼ ls admin.py api context_processors.py crypto.py decorators.py fixtures __init__.py middleware.py payment.py signals.pyc tests urls.pyc webservice admin.pyc apps.py context_processors.pyc crypto.pyc decorators.pyc formats … -
How to override RetrieveAPIView of django
I wrote a API that gets some of logged-in User or request.user by overriding APIView. But I want to reduce the number of lines of code by using generics.RetrieveAPIView somehow. The thing is that RetrieveAPI originally work with pk or id of an object whereas I want using request.user.id instead of pk. So Can I do that with RetrieveAPIView and how can i do that. Any help is appreciated ^^ -
python, django form duplicates label text
As time allows, I am messing around with Django. I have been paying attention to some tutorials and was following this one today on using django-widget-tweaks to add Bootstrap to forms. It "works" but I just noticed something odd. I am creating a required "profile" form on User-X's first login. That model&form have two "address" fields. The model names them "Address1" & "Address2". However, when the form is rendered the label text for Address2 is "Address1". The lavel is correct for the Address1 field. The psrt of the form involved: ... {% for field in profileForm.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% if profileForm.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} {% render_field field class="form-control is-valid" %} {% endif %} {% else %} {% render_field field class="form-control" %} {% endif %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> {% endfor %} <button type="submit">Submit</button> </form> ... From views.py: ... def create_profile(request): if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): pass # does nothing, just trigger the validation else: form = ProfileForm() … -
Django Rest Framework serializer `source` giving weird required error
I have an API that sends me fields with field names that don't match the ones in my model (and that I have no control over) and am trying to map them in the serializer, but for some reason I'm getting the following error: { "phone": [ "This field is required." ], "first_name": [ "This field is required." ], "last_name": [ "This field is required." ], "messenger_id": [ "This field is required." ], "email": [ "This field is required." ], "address": [ "This field is required." ] } when I actually implement this: class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField(source='customer_email') first_name = serializers.CharField(source='first name') last_name = serializers.CharField(source='last name') address = serializers.CharField(source='customer_address') phone = serializers.CharField(source='customer_phone') messenger_id = serializers.IntegerField(source='messenger user id') class Meta: model = User fields = ('id', 'url', 'email', 'first_name', 'last_name', 'address', 'phone', 'messenger_id',) However, among those fields, the only one that's actually required in my model is the email field. I used the source= parameter according to the top rated answer here, but am not sure what's causing the issue here. Thanks! -
Django admin for categories and objects
I have objects and catetories in Django and object has ForeignKey to Category. In Admin user must first create categories and then create objects choosing category from list. What I want to have is file manager metaphore: User opens list of categories, clicks "create object here" and creates one like we do it with folders and files. I wonder if Django has some application for it. Does it? -
Fix a unittest in Django
ERROR: test_dont_remember_cc (p38.tests.test_stripepayment.StripePaymentTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/infinity/.virtualenvs/p38-1/src/p38/p38/tests/test_stripepayment.py", line 70, in test_dont_remember_cc self.pay(mock_cc(brand='Visa', extra={'amount': '1.00', 'cc_hash': 'new', 'remember_cc': False})) File "/home/infinity/.virtualenvs/p38-1/src/p38/p38/tests/test_stripepayment.py", line 47, in pay self.client.post(reverse('zoneclient-payment'), cc, follow=follow) File "/home/infinity/.virtualenvs/p38-1/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 551, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/home/infinity/.virtualenvs/p38-1/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 468, in _reverse_with_prefix (lookup_view_s, args, kwargs, len(patterns), patterns)) NoReverseMatch: Reverse for 'zoneclient-payment' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P<clientcode>[0-9]{9})/payment/$'] Here is the unit test def test_dont_remember_cc(self): self.signin() self.pay(mock_cc(brand='Visa', extra={'amount': '1.00', 'cc_hash': 'new', 'remember_cc': False})) rs = self.client.post(reverse('zoneclient-payment'), {'amount': '1.00', 'quickform': True}) m = re.search('(var cards =.*)(card_\w+)"(.*)(Visa|Mastercard)', rs.content) self.assertEqual(m, None) self.assertEqual(200, rs.status_code) and the url is # Online payment url(r'^(?P<clientcode>[0-9]{9})/payment/$', csrf_exempt(login_required(OnlinePaymentView.as_view())), name='zoneclient-payment'), It is unclear how to fix that test. Any help?