Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to generate a public token in django JSONWebTokenAuthentication
I am using the django rest framework, and I am using the JSONWebTokenAuthentication. For some APIs, that don't require the user to be registered, I need to authenticate the user based on a public token that will be stored on the client side. Is this possible in JSONWebTokenAuthentication in the restframework. Thanks -
How to add average of nested relation in DRF
Question How can I add a new field avg_rating to Musician model which represents the avg of their albums rating (sum_of_rating / num_of_albums_in DB) I have two models, class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) class Album(models.Model): artist = models.ForeignKey(Musician, on_delete=models.CASCADE) name = models.CharField(max_length=100) release_date = models.DateField() num_stars = models.IntegerField() and serializer as, class AlbumSerializer(serializers.ModelSerializer): artist = serializers.StringRelatedField() class Meta: fields = '__all__' model = Album class MusicianSerializer(serializers.ModelSerializer): albums = AlbumSerializer(many=True, source='album_set') class Meta: fields = '__all__' model = Musician views, class AlbumViewset(ModelViewSet): serializer_class = AlbumSerializer queryset = Album.objects.all() class MusicianViewset(ModelViewSet): serializer_class = MusicianSerializer queryset = Musician.objects.all() and I got respons as, [ { "id": 1, "albums": [ { "id": 1, "artist": "Musician object", "name": "Scorpion", "release_date": "2018-07-24", "num_stars": 4 }, { "id": 2, "artist": "Musician object", "name": "More Life", "release_date": "2017-07-24", "num_stars": 4 }, { "id": 3, "artist": "Musician object", "name": "Views", "release_date": "2017-07-24", "num_stars": 3 }, { "id": 4, "artist": "Musician object", "name": "Take Care", "release_date": "2011-07-24", "num_stars": 5 } ], "first_name": "Drake", "last_name": "Graham", "instrument": "Sitar" }, { "id": 2, "albums": [ { "id": 5, "artist": "Musician object", "name": "Voicenotes", "release_date": "2018-07-24", "num_stars": 5 }, { "id": 6, "artist": "Musician object", "name": "Nine … -
Using django template to html table
I want to design a table can compare with each other by year. my data like this: book Data Image # views.py def bybook(request, bookName='A-Book'): bookdata = models.bookdb.objects.filter(bookName=bookName).order_by('Year', 'point') return render(request, 'book.html', locals()) I hope result want: enter image description here What i have tryed django templates regroup https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#regroup but can't achieve my require. what can i do? Thank you for any help in getting started prior! Best Regards -
psycopg2.ProgrammingError: can't adapt type 'numpy.int64'
I have a dataframe to read a excel file and then go through it to fill my modal. But when I execute this .py file, the output is the following: /usr/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 return f(*args, **kwds) Traceback (most recent call last): File "llenar_tabla_bonos_fonasa.py", line 43, in <module> cur.execute(query, data) psycopg2.ProgrammingError: can't adapt type 'numpy.int64' The line 43 corresponds to cur.execute(query, data) I tried following the next posts but none works: Scipy error: numpy.dtype size changed, may indicate binary incompatibility (and associated strange behavior) RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility Some suggestion? Thanks everyone! -
Django-admin module name not found?
I am using django version 1.6.11 and when I want to create the project by using command django-admin startproject mysite it throws the errorC:\Python27\python.exe: No module named django-admin and when I use django-admin.py startproject mysite it opens a new file named dajngo-admin.py. I don't know what the issue is as when I open a already created django project I am able to run the project using python manage.py runserver but then also I am not able to create new app inside the project as it requires django-admin startapp. -
Requested setting ORIGINAL_BACKEND, but settings are not configured
I got a problem in my first code when I tried "django multytenancy" I followed this tutorial: Django Tutorial - Multi Tenant Setup My code : mycode @ github and my result: python manage.py shell Traceback (most recent call last): File "manage.py", line 2, in <module> from tenant_schemas.models import TenantMixin File "/usr/local/lib/python2.7/dist-packages/tenant_schemas/models.py", line 4, in <module> from tenant_schemas.postgresql_backend.base import _check_schema_name File "/usr/local/lib/python2.7/dist-packages/tenant_schemas/postgresql_backend/base.py", line 13, in <module> ORIGINAL_BACKEND = getattr(settings, 'ORIGINAL_BACKEND', 'django.db.backends.postgresql_psycopg2') File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting ORIGINAL_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Thank you for the help. -
How to display gmplot's marker on Django's template HTML
I am trying to use gmplot for the first time. And I'm new programming. I could use gmplot almost no problem. It creates a html map which has some lines or markers. I'd like to use that html map as django's template html. I could display a map as rendering html. But I have a problem. It doesn't display markers. It display the map has only plotted lines. Browsing the html not through django, the map displays lines and markers correctly. So I think gmplot itself works fine. How can I display marks correctly as django's rendering html ? Thank you for any help you can provide. -
NoReverseMatch at /13/download/ in Django
I have been trying to develop a small application using Django. Everything was working fine. Then, I added a "download" button to send mail to the user. Whenever I click on that button I get this error: NoReverseMatch at /13/download/ Reverse for 'about' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<pk>[0-9]+)/about/$'] My views.py : def download(request,pk): if not request.user.is_authenticated: return render(request, 'set_goals/index.html') else: user = request.user immediate = {} necessary = {} longterm = {} notnecessary = {} try: immediate = get_object_or_404(Immediate, user_id=pk) necessary = get_object_or_404(Necessary, user_id=pk) longterm = get_object_or_404(Longterm, user_id=pk) notnecessary = get_object_or_404(NotNecessary, user_id=pk) except: print("error somewhere") pdf = render_to_pdf('set_goals/all_goals.html',{'notnecessary':notnecessary,"immediate":immediate,"longterm":longterm,"necessary":necessary}) if pdf: print("yes pdf") response = HttpResponse(pdf, content_type='application/pdf') filename = "Goals.pdf" content = "inline; filename='%s'" % (filename) message = EmailMessage("Hello","These are your goals","8888888888@gmail.com",['999999999999999@gmail.com']) message.attach('mypdf.pdf',pdf,'application/pdf') message.send() return render(request,'set_goals/all_goals.html',{'notnecessary':notnecessary,"immediate":immediate,"longterm":longterm,"necessary":necessary}) return render(request,'set_goals/index.html') urls.py : from django.conf.urls import url,include from . import views app_name = 'set_goals' urlpatterns = [ url(r'^$',views.index,name='index'), url(r'^(?P<pk>[0-9]+)/about/$',views.about,name='about'), url(r'^(?P<pk>[0-9]+)/download/$', views.download, name='download'), ] template : {% extends 'base.html' %} {% block title %}Immediate{% endblock %} {% block content %} <div class="container"> {% if user.is_authenticated %} <div class="container"> <div class="row"> <div class="col-md-6"> {% if immediate.body %} <h2>{{immediate.title}}</h2> <pre>{{immediate.body}}</pre> {% else %} <h2>Immediate Goals</h2> <p>Yet to be placed!</p> {% endif %} </div> … -
Django database migration error (sqlite3->postgre)
I have created an app using django, now I am trying to use anther database instead of its default which is sqlite3. I have chosen postgres. When I run the command python3 manage.py makemigrations I get the following erros: Traceback (most recent call last): File "/root/mypro/env/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "banners_supercat" does not exist LINE 1: ...supercat"."id", "banners_supercat"."english" FROM "banners_s... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/root/mypro/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/root/mypro/env/li ... what is the problem and what should I do? -
Django: Display text for multi select option in template
So, when you use a positivesmallint field for a multiple choice question opti= models.PositiveSmallIntegerField(choices=OPTION1_CHOICES, default=4), you can display the text by doing the following: OPTION1_CHOICES=( (1, ("a")), (2, ("b")), (3, ("c")), (4, ("d")), ) {{ object.get_option1_display }} However, when you have a multiselect field option2 = MultiSelectField(choices=OPTION2_CHOICES)the following doesn't work: OPTION2_CHOICES= ( ( 'e','E'), ( 'f', 'F'), ( 'g','G'), ) {% for option in object.option2 %} {{ get_option_display }} {% endfor %} -
Django comments custom user profile avatar
I'm using Ajax Comments Systeme to render comments and the form and I have a custom user profile that include avatar field class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default="") avatar = ImageField('userprofile', default='avatars/default.png', upload_to="avatars" ) In a regular view i used to do: from Profiles.models import UserProfile def BlogPost(request, slug): post_slug = posts.objects.get(slug=slug) author_avatar = Author.objects.get(user=User.objects.get(username=post_slug.author).id).avatar.url args = { 'post_slug': post_slug, 'author_avatar': author_avatar, 'related': _related(post_slug.tags), } return render(request, "blog_post.html", args) But Now I'm stack on getting every commentator avatar ... I need solution even if I used to modify the package or override it -
Django Rest Framework giving empty Response
I'm implementing a simple web application where front-end is Angular and back-end is Django. I'm sending a login request from Angular which is getting a 200 OK response, but the response body is empty (doesn't have the token data). This is my APIView file. from django.contrib.auth import authenticate from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response class LoginView(APIView): permission_classes = () def post(self, request,): username = request.data.get("username") password = request.data.get("password") user = authenticate(username=username, password=password) if user: print(user.auth_token.key) return Response({"token": user.auth_token.key}) else: return Response({"error": "Wrong Credentials"}, status=status.HTTP_400_BAD_REQUEST) I checked token is getting generated by printing it right before the Response line. Another interesting thing is when I tried the API from Postman, I'm getting the token in the response. Also, the user register API implemented using ViewSet is working fine and is returning correct response. -
form not being sent to django url
I have jquery that adds a table row to my table body after form submission function asset_create_post(){ console.log("asset_create_post is working") var asset_category = $('#asset_category').val() console.log(asset_category) $.ajax({ url : "/money/assets/", type: "POST", data : { 'asset_name' : $('#asset_name').val(), 'asset_amount': $('#asset_amount').val(), 'asset_category': $('#asset_category').val() }, success : function(json) { var url = "{% url 'money:delete_asset' %}"; $('#asset_name').val() console.log(json) console.log('success') $('#tableBody').append('<tr id="hover"><td>'+json.asset_category+'</td><td>'+json.asset_name+'</td><td>'+json.asset_amount+'</td><form method="POST" action='+url+'><td id="end_cell"><input type = "hidden" class="delete_button" value='+json.asset_id+'><button type="submit" class="delete_button">Delete</button></input></td></form></tr>'); }, error: function(xhr, errmsg,err){ console.log('fail') } }); }; when I click on the delete button the button does nothing. I'd like to send the json.asset_id to my money:delete_asset URL...any advice? -
Django Custom User Model without Username or Password
I am trying to make a REST API for a simple web app in django that allows users to upload files. (Each user is associated to another model, say Department). However, in order to interact with the Rest API I want to generate an API key and secret (ApiUser) for the department and authenticate using JWT. A department can have multiple ApiUsers. Each ApiUser is identified by a CharField, alias and is linked to the Department. Current approach: My ApiUser model extends models.Model class and has a is_authenticated method that returns True. Note that ApiUser has no username, password, or email fields. The file to be uploaded has two fields.i.e. uploader for default User model, and api_uploader for ApiUser model. What I want is to extend ApiUser from the User model so that I can have a single AUTH_USER_MODEL and a single field for uploader for the files. -
How to attach an existing CSV file to an email?
I'm trying to follow the example at Attach generated CSV file to email and send with Django to generate a CSV file and send it by email. In my case, however, I would also like to save the actual file, and not only send it my email as in the example. (Also, I'm using Python 3, whereas the example seems to pertain to Python 2). Here is the Django script I'm trying to run: import csv from collections import OrderedDict from datetime import datetime from django.conf import settings from django.core.mail import EmailMessage from lucy_web.models import Family # Path of the CSV file to generate and send by email (relative to lucy-web) FILENAME = 'scripts/nps.csv' def get_row(family): """ Return a row for the spreadsheet, including the corresponding headers. (The actual argument to csv.write.writerow() should be the .values(); the .keys() are for the header row). (An OrderedDict is easier to read/add to than two separate lists). """ return OrderedDict([ ("Employee Name", family.employee_name), ("Employee Email", family.employee_email), ("Employee Alternate Email", family.employee_alternate_email), ("Partner Name", family.partner_name), ("Partner Email", family.partner_email), ("Partner Alternate Email", family.partner_alternate_email), ]) def run(): write_csv_file() send_results_by_email(to=['kurt@hicleo.com']) def write_csv_file(filename=FILENAME): """Generate a CSV file with NPS data""" with open(filename, 'w', newline='') as csvfile: writer = csv.writer(csvfile) … -
How to fix install mysqlclient ?
How to fix install mysqlclient ? I comment 'pip install mysqlclient' Image error -
How do I access a Django model attribute within the model class definition?
The problem with this code is that when I try to access 'self.username' I get a NameError: 'self' is not defined. The username attribute is inherited from Django's AbstractUser. I did some googling and found that I needed to make an init method in order for the self variable to exist. The problem is that I do not want to do anything in the init since the rest of my Django code handled the instantiation already and my application is working as is. I tried making an init method with just 'pass' but this also gives me the same error. Is there any way I can access my attribute without seriously changing the model or making new migrations? I am using Django 2.0 on a Windows 10 OS. -
django how to check the type of a file uploaded from mobile
I created a django app which lets users upload music and play them online This is my model from django.db import models class Song(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=100,null=False,blank=False) artist=models.CharField(max_length=100,null=False,blank=False) user=models.ForeignKey(User,null=False,blank=False) file = models.FileField(null=False,blank=False) def __str__(self): return self.artist+" - "+self.title I created a view that adds a new song to the currently logged user, by checking if the file type is audio or not def add(request): if 'logged' not in request.session: return HttpResponseRedirect('/') elif request.method=='POST': title=request.POST.get('title').strip() artist=request.POST.get('artist').strip() if title and artist: user=request.session['user'] song=Song(title=title,artist=artist,user=user) if len(request.FILES) != 0: file = request.FILES['file'] ext = os.path.splitext(file.name)[1] if ext in ['.mp3', '.wav']: song.file=file song.save() return HttpResponseRedirect('/') The problem is that it doesn't work for mobile because by default the file system hides the extension so when I submit the file there's no extension and django thinks that the file is not valid when in fact it is I guess I should be looking for other alternatives but I don't know how. -
Django: ChoiceField choices are hidden in the template
When using a ChoiceField in my form in my django app, The options and Select tags appear in the source code (inspector) but not in page. The problem does not occur when using CharField. I get the choices from my models, Yet even when I set the choices manually, the problem persists. Here is the Forms.py: from django import forms from .models import Placard, Agent class FormDossier(forms.Form): j = 0 placard_options = [] agent_options = [] for i in Placard.objects.all().order_by('rang'): tup = str(j), i.rang placard_options.append(tup) j=j+1 for i in Agent.objects.all().order_by('numero_de_somme'): tup = str(j), i.numero_de_somme agent_options.append(tup) j=j+1 f_agent = forms.ChoiceField(widget=forms.Select, choices=agent_options,label = "رقم التأجير" ) f_placard = forms.ChoiceField(widget=forms.Select, choices=placard_options,label = "الخزانة") f_tiroir = forms.CharField(label = "الرف") View.py def CreateDossier(request): form = FormDossier(request.POST or None) if form.is_valid(): _p = form.cleaned_data['f_placard'] _a = form.cleaned_data['f_agent'] t = form.cleaned_data['f_tiroir'] p = Placard.object.get(rang=_p) a = Agent.object.get(numero_de_somme=_a) Dossier(agent=a, placard=p, tiroir=t) return HttpResponseRedirect('/') return render(request, 'dossier/create.html', locals()) The template <div class="row"> <form method="post" class="col s12"> <div class="row"> {% csrf_token %} {{ form.as_p }} </div> </form> </div> -
django user registration form
Im trying to change the Django registartion form. I dont wish to login with username, only by email. Thats why Im searching for a way to ignore or replace the username field from Django auth_user my forms.py class registForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ('email', 'password1', 'password2', ) I tried to add username = forms.CharField(default=email) or username = forms.CharField(max_length=50, widget=forms.HiddenInput(), initial={'Hello World'}) But the system dont allow to add username on this way. I tried also this way in models.py class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) USERNAME_FIELD = 'email' and in settings.py AUTH_USER_MODEL = 'account.MyUser' #my app name is account But I get this Error message E:\pycharmprocects\test_account>python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: account.Profile.user: (fields.E301) Field defines a relation with the model 'aut h.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. does anyone happen to know how I can solve this? -
able to return nested dictionary using values? django
let's say if I have a model named Blog and this is how the value works >>> Blog.objects.values() [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}], >>> Blog.objects.values('id', 'name') [{'id': 1, 'name': 'Beatles Blog'}] but let's say if I want to make the name into another dict and get such in return [{'id': 1, 'blog': { 'name': 'Beatles Blog'}}] is the above possible by using value or something similiar? I know I can do something like which would work [{'id': blog.pk, 'blog': {'name': blog.name}} for blog in blogs] Thanks in advance for my curiosity -
Adding multiple inputs by user dynamically
I'm new to Django 2.0. I'm working on a project where I need users to input questions (from at least 1 to as much as they want). Like after adding one question they should have option if they want to add more in the same form field (like if I have a Textarea field it should be accepting multiple Textarea fields and can be displayed separately). How can I do this, please let me know, thank you. -
GeodDjango: Move a Point east by one mile
Given a Point (django.contrib.gis.geos.Point) how do I find another point 1 mile east from that Point object? (A) ---[ 1 mile ]---> (B) My failed attempts: I've considered trying to go hardcode the 1 mile east point but due to the curvature of the earth. The miles per degree change. Copius googling on SO and Geo Info Exchange. I assume I cannot find the terminology? Python 3.6 Django 1.11 -
Django resolve() doesn't resolve a valid path
I want to run test in Django, and I have a very simple test case that aims to test whether an url is reachable. I am using a valid path, but I still get a Resolver404 error. I don't know if it has something to do with multilanguage settings, or something. This is my main urls.py: from django.contrib import admin from django.conf.urls.i18n import i18n_patterns from django.urls import path, include from rest_framework.authtoken import views from django.conf.urls.static import static from django.conf import settings urlpatterns = i18n_patterns( path('api-token-auth/', views.obtain_auth_token), path('', include('FrontEndApp.urls')), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('rosetta/', include('rosetta.urls')), path('general/', include('GeneralApp.urls')), #path('invoices_manager/', include('InvoicesManagerApp.urls')), path('operations_manager/', include('OperationsManagerApp.urls')), #path('payments_manager/', include('PaymentsManagerApp.urls')), #path('providers_manager/', include('ProvidersManagerApp.urls')), path('rates_manager/', include('RatesManagerApp.urls')), #path('reports_manager/', include('ReportsManagerApp.urls')), path('reservations_manager/', include('ReservationsManagerApp.urls')), path('users_manager/', include('UsersManagerApp.urls')) ) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is my app urls.py: from django.urls import path, include from GeneralApp import views, models from rest_framework import routers, renderers APP_NAME = 'GeneralApp' urlpatterns = [ path('', include(router.urls)), path('catalogs/', views.CatalogViewSet.as_view({'get':'list'})), path('countries/', countries_list, name='rest_countries_list'), path('countries/<int:pk>/', country_detail, name='rest_country_detail'), path('countries/<int:pk>/states/', states_list, name='rest_country_states_list'), path('states/', states_list, name='rest_states_list'), path('states/<int:pk>/', state_detail, name='rest_state_detail'), path('states/<int:pk>/cities/', cities_list, name='rest_state_cities_list'), path('cities/', cities_list, name='rest_cities_list'), path('cities/<int:pk>/', city_detail, name='rest_city_detail'), path('cities/<int:pk_city>/zones/', city_zones_list, name='rest_city_zones_list'), path('zones/<int:pk>/', zone_detail, name='rest_zone_detail'), path('zones/', zones_list, name='rest_zones_list'), path('airports/<int:pk_city>/airports/', city_airports_list, name='rest_city_airports_list'), path('airports/', airports_list, name='rest_airports_list'), path('airports/<int:pk>/', airport_detail, name='rest_airport_detail'), path('languages/', languages_list, name='rest_languages_list'), path('languages/<int:pk>/', language_detail, name='rest_language_detail'), path('provider_types/', provider_types_list, name='rest_provider_types_list'), path('provider_types/<int:pk>/', provider_type_detail, … -
Django 2.0 Form is not saving data to database
so I have a very simple blog app and I'm trying to figure out why the data entered in the form doesn't save to the database and it doesn't redirect me to my index page. forms.py from django import forms class NewBlog(forms.Form): blogger = forms.CharField(max_length=20, widget=forms.TextInput(attrs= {'placeholder' : 'Name'})) text = forms.CharField(widget=forms.Textarea(attrs={'placeholder' : 'Text'})) new_blog.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>New Blog</title> </head> <body> <form action="{% url 'new_blog' %}" method="POST"> {% csrf_token %} <h2>Write your blog here:</h2> {{ form }} <br> <input type="submit" value="Submit"> </form> </body> </html> views.py from django.shortcuts import render, redirect from .models import BlogPost from .forms import NewBlog def index(request): blogs = BlogPost.objects.all() context = {'blogs' : blogs} return render(request, 'blog/index.html', context) def newBlog(request): if request == 'POST': form = NewBlog(request.POST) if form.is_valid(): blogger = form.cleaned_data['blogger'] text = form.cleaned_data['text'] new_blog = BlogPost(blogger = blogger, text = text) new_blog.save() return redirect('index') else: form = NewBlog() context = {'form' : form} return render(request, 'blog/new_blog.html', context)