Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django user authentications via Google ID Token
I am beginner to Django. I am trying to create back-end for my Android app. I generated Google ID Token in my Application and followed this documentation to send the ID token to my server and verified the integrity of the ID token using google-api-python-client library. Now I don't know how to proceed to authenticate as a Django user? I googled for hours there are plenty of tutorials about this but most of them are pointing towards some sort of web front-end and then authenticate. I am not building a website, I am building an Android App back-end. How do I proceed from this point?? I don't need any code just guide a right path to move further? -
Form checkboxes for boolean model fields disappear when applying Materialize CSS
In my Django application, there are models with boolean fields. Objects related to the model should be able to be manipulated by the application users. Example model: class Example(models.Model): Attr1 = models.DateTimeField(default=timezone.now) Attr2 = models.BooleanField(default=False) Attr3 = models.BooleanField(default=False) The way users can manipulate the value of Attr2 and Attr3, is by using model forms: class FormExample(forms.ModelForm): class Meta: model = Example fields = ('Attr2','Attr3',) This works perfectly when passed to a plain HTML template, as the user will see checkboxes marked when the boolean value is TRUE, and unmarked when it is FALSE. These checkboxes can be changed by clicking on it, which is immediately reflected by the object values in the database after saving: <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> However, when applying my base which includes Materialize CSS, the HTML page is styled as expected BUT the checkboxes have disappeared (making the form useless): {% extends "base.html" %} {% block content %} <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> {% endblock content %} I have read about similar issues where checkboxes disappear after applying Materialize. However, I could not find a suitable solution to my problem yet. This looks … -
Removing duplicates due to order by fields from a related model
I have 2 different models in the same app class Book(models.Model): title = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=50) description = models.TextField(max_length=500) class Chapter(models.Model): book = models.ForeignKey(Book,on_delete=models.CASCADE) num = models.PositiveIntegerField(verbose_name="Chapter Number") rdate = models.DateTimeField(verbose_name="Release Date", default=timezone.now) What I want to do is get all books ordered by descending of release date rdate What I tried is: Book.objects.all().order_by('-chapter__rdate').distinct() Some duplicates were found in result, I only had 2 books added, so only 1 book was duplicated. The result was something like this: Book1, Book2, Book2 I have already seen the note from here, and im using SQLite. By using values(), I won't be able to call get_absolute_url() and some other methods that I want to call so using values() is out of question. Next I tried to annotate the Chapter rdate into Book query like this Book.objects.all().annotate(bdate=ExpressionWrapper(F('chapter__rdate'), output_field=DateTimeField())).order_by('-bdate').distinct() Still ended in the same result. I'm totally lost, please need help. I probably won't change to PostgreSQL now, but I might use it when I deploy the app, so I want both SQLite version and PostgreSQL version solutions for this if at all possible. SQLite solution is absolutely necessary for me since it's easy to use in development. -
Helper classes in Django
I have a Django 1.11 project, using the Django Rest Framework, and inside the project, an app called Foo. I also have a helper class inside the Foo app. Folder structure looks like this: project/ │ ├─ foo/ │ ├─ api/ │ │ ├─ __init__.py │ │ ├─ views.py │ │ ├─ helper.py helper.py: class Helper(): name = None def get_name(self, data): # Do something with data return self.name views.py: from rest_framework.generics import ListAPIView from foo.api.helper import Helper class FooAPIView(ListAPIView): def get_queryset(self): data = 1234 name = Helper.get_name(data) My problem is that when hitting the API endpoint, I get this error: get_name() missing 1 required positional argument: 'data' -
Type error on Login using the 'login()' function
Here is the Code, I just write it as usual. And I never got this error before. The error says : TypeError at /accounts/login/ init() takes 1 positional argument but 3 were given. Exception Value : init() takes 1 positional argument but 3 were given. Exception Location: C:\Dev\Django\MyRecipe\accounts\views.py in post, line 26. Here is the link : https://hastebin.com/judivetasa.rb error at login(self.request, user) -
Complex django query, getting objects whose foreignkey_set does not contain an object that satisfies a restriction
I have a model, foo, and a model bar. bar has a foreignkey to foo, as well as a days field, which is a postgresql DateRangeField class Foo(models.Model): baz = models.CharField() class bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) days = DateRangeField() I need to do a query, given a date (day), and a baz: get all Foo objects that satisfy baz = baz, and that do not have an associated bar object that satisfies days.lower < days < days.upper (or in other words, do not have day within the range of their days variable. I've looked at Q queries, but the only way I've found to do it so far is to get all Foo objects that satisfy baz=baz and then use python to do the rest of it (which is clearly inefficient in terms of DB queries). -
How to convert ImageString to Image Django Rest Framework?
I am recieving my image string from android using Asynchttp and well i want to convert that image string to an Image in Django Rest Framework..Just convert it not to store it in an ImageField *Model.py class Food(models.Model): label=models.TextField(max_length=200) link = models.FileField(null=False, blank=False) Image = models.TextField(link, null=True) class Android(models.Model): label=models.TextField(max_length=200) imagestring=models.TextField(null=True,blank=True) //convert this to Image *Serializer.py class AndroidSerializers(serializers.HyperlinkedModelSerializer): class Meta: model = Android fields = ('label', 'imagestring') class FoodSerializers(serializers.HyperlinkedModelSerializer): class Meta: model=Food fields=('url','label','Image','link') *Views.py class FoodViewSet(viewsets.ModelViewSet): queryset = Food.objects.all() serializer_class =FoodSerializers class Androids(viewsets.ModelViewSet): queryset =Android.objects.all() serializer_class = AndroidSerializers() -
How to use s3upload to upload file directly without form?
I'm using s3upload to upload image using admin form. How can I avoid using form for uploading (selecting file through explorer) and upload file using some method (like upload("filename.jpg"))? Is it possible? -
Django not sending error messages to email
I used to be able to do this, not sure why it seems to no longer work. I want Django to email me whenever an error occurs like 500 server error, which would be useful since the email usually includes the detailed error description. Here's one error I'm letting persist for now shown in chrome's terminal as I try and get this feature to work. here's what I have in my settings file ADMINS = ['<my_email>'] EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = SERVER_EMAIL = '<server_email>' EMAIL_HOST_PASSWORD = "xxxxxx" # EMAIL_USE_TLS = True so even though this is an error it doesn't send any emails to my mail. I can however send emails from the shell using from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', '<server_email>', ['<my_email>'], fail_silently=False, ) from the same server -
Why is my hosted Django app showing my username in the URL?
I've written a Django app which I'm trying to get set up on shared web hosting (A2). It's working, except that when I go to http://mycoolsite.com/terms/, for example, the URL changes in the browser bar to http://mycoolsite.com/home/myusername/myappfolder/myappname/terms/, showing the full path to where my app is on disk. This doesn't happen with static files - e.g. http://mycoolsite.com/static/mycoolimage.png works normally. The app is running in a virtual environment. I'm using python 3.6.8 and Django 2.1.4. I followed these instructions to set up my app, which include setting up this passenger.wsgi file, that looks like this: import myapp.wsgi SCRIPT_NAME = '/home/username/myapp' class PassengerPathInfoFix(object): """ Sets PATH_INFO from REQUEST_URI because Passenger doesn't provide it. """ def __init__(self, app): self.app = app def __call__(self, environ, start_response): from urllib.parse import unquote environ['SCRIPT_NAME'] = SCRIPT_NAME request_uri = unquote(environ['REQUEST_URI']) script_name = unquote(environ.get('SCRIPT_NAME', '')) offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0 environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0] return self.app(environ, start_response) application = myapp.wsgi.application application = PassengerPathInfoFix(application) I'd be grateful for any pointers as to where to look to solve this. -
How to structure my Django web scraping project?
I'm fairly new to programming and still have some issues structuring my projects in Django. I'm setting up a web scraper application and my goal is to visualize the scraped data and return it in different kinds of diagrams. At the moment I've the scraping code in the views.py file. My question is: Is there a preferred directory structure for this kind of applications? I was thinking about: -setting up the scraping code in a new scrape.py -setting up models to feed the data to in models.py -setting up the visualization code in the views.py This is my views.py atm : from django.shortcuts import render from django.views.generic import TemplateView import requests from bs4 import BeautifulSoup def PlayerDetailView(request): first_name = 'Drew' last_name = 'Brees' last_name_first_letter = last_name[0] last_name_first_four = last_name[0:4] first_name_first_two = first_name[0:2] page = requests.get('https://www.pro-football-reference.com/players/{}/{}{}00.htm'.format(last_name_first_letter, last_name_first_four, first_name_first_two)) content = page.content week_number = 251 stats = soup.find("tr", {"id": "stats.{}".format(week_number)}) stats_relevant = ['pass_yds', 'pass_td', 'rush_yds'] stat_list = [] for stat in stats_relevant: stat_list.append(int(list(stats.find("td", {"data-stat": "{}".format(stat)}).children)[0])) dic_list = {'tag':stat_list} return render(request,'league_app/player.html', context=dic_list) Thank you in advance! -
How to fix "Incorrect value" in 'django-rest-auth" library?
I am trying to setup Facebook social auth via django-rest-auth. I followed the official tutorial. 1.Added needed apps to INSTALLED apps 2. Created view from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter from rest_auth.registration.views import SocialLoginView class FacebookLogin(SocialLoginView): adapter_class = FacebookOAuth2Adapter Added url urlpatterns += [ ..., url(r'^rest-auth/facebook/$', FacebookLogin.as_view(), name='fb_login') ] Created social app(I have used 2 different facebook apps to test different public and secret keys). I got access_token from https://developers.facebook.com/tools/explorer Tried to send access_token to my url via postman and django-rest-framework(directly in browser) All times I have got an error: { "non_field_errors": [ "Incorrect value" ] } I tried to create new project only with django-rest-auth setup - same issue. Yesterday I've got success with this flow but today it doesn't work at all... -
Python Regex search bad escaping
This has been bugging me and I can't seem to find a fix. I have a function that has worked since I don't know when, that searches a binary file for a byte string... foo = abin.read() bar = re.search(b'\x03\NIBA', foo) Since updating to win 10 and django 2.10 - I now get an error... bad escape \N at position 1 I am missing encoding parameters or such? double escaping doesn't fix. -
Seperate files uploaded through different input tags at POST
Problem Description: I have a django view and template which displays several paragraphs of data, which are retrieved from a Model. Below each one, is a <input type="file"> tag, for uploading images related to each row of data. When user uploads files, he may upload 1 to several files for one particular row of the model, or he may choose not to upload files for one or more models. I need to save these files with a foreign key to that particular row. I am not using django forms for this. My model: class Procedure(models.Model): procid = models.AutoField(primary_key=True, unique=True) timestr = models.DateTimeField(default=timezone.now) template = models.ForeignKey(ProcedureTemplate, on_delete=models.CASCADE, blank=True, null=True) clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE) doctor = models.ForeignKey(doctor, on_delete=models.SET_NULL, blank=True, null=True) customer = models.ForeignKey(customer, on_delete=models.CASCADE, null=False) def __str__(self): return f'{self.template} for {self.customer} on {self.timestr}' class SectionHeading(models.Model): procid = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=200) fieldtype_choice = ( ('heading1', 'Heading1'), ('heading2', 'Heading2'), ) fieldtype = models.CharField( choices=fieldtype_choice, max_length=100, default='heading1') template = models.ForeignKey(ProcedureTemplate, on_delete=models.CASCADE, null=False) def __str__(self): return f'{self.name} [{self.procid}]' class SectionText(models.Model): procid = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=200) widgettype_choice = ( ('textarea', 'Textarea'), ('text', 'Short Text'), ) widgettype = models.CharField( choices=widgettype_choice, max_length=100, default='text') heading = models.ForeignKey(SectionHeading, on_delete=models.CASCADE, null=False) def __str__(self): return f'{self.name} [{self.procid}]' class SectionImage(models.Model): … -
How to write cron file for upload local files into s3 bucket at every hours in django rest framework
In django rest framework, I can upload files into 'local path' or 's3 bucket' directly. My Question is first I want to upload files into local path and after specific time (e.g one hour) I want to upload it into s3 bucket. But in API GET should be display the s3 bucket path url for files. If anyone have with any example codes or documentation, please comment -
I can't execute command 'electroshot' installed with npm in a django app served in IIS
I want to execute 'electroshot' command, is for creating pdf from a html, the problem is when the django app is serve on IIS give me following error: 'electroshot' is not recognized as an internal or external command, operable program or batch file. Serving the app with django runserver works correctly. Here is the code when i execute the command: filename = "file.html" fScript = r"""electroshot file://{0} 1920x1024 --format pdf --pdf-background""".format(filename) subprocess.call(fScript, stdout=open("myoutput","w"), stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, shell=True) I send the stdout to a file to check the error,that is 'electroshot' is not recognized as an internal or external command, operable program or batch file. I have LocalSystem in ApplicationPoolIdentity. -
How to access variables in Django url?
I have been trying to access the variables in the redirect I get from lyrebird API which is like: http://website.com/auth/lyrebird#access_token=value1&token_type=bearer&state=value2 I am not able to access this access_token via GET or POST. Any help is appreciated. -
{"username":["This field is required."]}
Stuck with the error here. Works fine with the get request in angular but create problem while using post request. So guys help me. And thanks in advance guys. serializers.py from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): """ Create and return a new user""" user = User.objects.create_user(**validated_data) return user view.py from django.contrib.auth.models import User from rest_framework import viewsets from .serializers import UserSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ serializer_class = UserSerializer queryset = User.objects.all() register/urls.py from django.urls import path, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register('users', views.UserViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), ] django/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('register.urls')), ] error -
How to trigger a function of class via button in view
I'm setting up an application working with Django and Keras. It takes a lot of time to take my uploaded document, prepare, train and to show my results. That's why I'm trying to split my code into different phases. But I don't know how to trigger a function using my created object before. Do you know how to connect a button to trigger a process via using created object? Thanks in advance! -
How to generate PDF in Django Generic Views?
I have a template that is rendered by generic List View. I want to give a download link in front of each row of data in table. The download link will create a PDF file of respective rows data. Please tell me how to write a code for that? Views.py class BookingConfirmationListView(LoginRequiredMixin, generic.ListView): model = container_booking template_name = 'home/booking_confirmation_detail.html' context_object_name = 'all_container' def get_queryset(self): return container_booking.objects.all() Templates look like <table class="table-striped table-hover table-bordered" width="100%"> <tr> <th>Date</th> <th>Source</th> <th>Destination</th> <th>Container</th> <th>Commodity</th> <th>Agreed Rate</th> <th>Edit</th> <th>Delete</th> <th>Status</th> </tr> {% for item in all_container %} <tr> <td>{{ item.date }}&nbsp;</td> <td>{{ item.place_of_reciept }}&nbsp;</td> <td>{{ item.final_place_of_destination }}&nbsp;</td> <td>{{ item.equipment_type }}{{ item.quantity }}&nbsp;</td> <td>{{ item.commodity }}&nbsp;</td> <td>{{ item.agreed_rate }}&nbsp;</td> <td><a href="{% url 'home:cont_bk-update' item.id %}" ><i class="fas fa-edit"></i></a></td> <td><a href="{% url 'home:cont_bk-delete' item.id %}" ><i class="fas fa-trash"></i></a></td> <td>{{ item.approved }}</td> </tr> {% endfor %} </table> urls.py url(r'^cont_bkdetail$', views.BookingConfirmationListView.as_view(), name='cont_bk-detail'), url(r'^cont_bk/(?P<pk>[0-9]+)/$', views.BookingConfirmationUpdate.as_view(), name='cont_bk-update'), url(r'^cont_bk/(?P<pk>[0-9]+)/delete/$', views.BookingConfirmationDelete.as_view(), name='cont_bk-delete'), I want that whenever I click download, the PDF file of that row is generated. -
Trigger jupyter python code with HTML button in django (index.html)
I have python code in jupyter notebook and html button in Django index.html .how I trigger python code (in jupyter) with help of html button (in Django) -
'status' is an invalid keyword argument for this function
I new to Django & Python. (Previously is PHP). I am having problem where I want to arhive custom model without DB blinding. The data for the model is come from raw SQL. I trying to find out how to get data from rawsql then insert to Object. I found this article Model Manager which look promising. After try & error. I get the error below: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/a/something Django Version: 2.1.5 Python Version: 3.7.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'phonenumber_field', 'user_accounts', 'shipments', 'CA', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'django.contrib.sites', 'allauth.socialaccount', 'dashboard'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\myfxhuta\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\myfxhuta\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\myfxhuta\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\myfxhuta\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "C:\Users\myfxhuta\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Users\myfxhuta\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rest_framework\views.py" in dispatch 495. response = self.handle_exception(exc) File "C:\Users\myfxhuta\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rest_framework\views.py" in handle_exception 455. self.raise_uncaught_exception(exc) File "C:\Users\myfxhuta\AppData\Local\Programs\Python\Python37-32\lib\site-packages\rest_framework\views.py" in dispatch 492. response = handler(request, *args, **kwargs) File "C:\Users\myfxhuta\Documents\Coding\python-testing\CA\dashboard\views.py" in get 23. "data" : consignment_status.objects.with_counts() File "C:\Users\myfxhuta\Documents\Coding\python-testing\CA\dashboard\models.py" in with_counts 22. p = self.model(consignmentNo=row[0], status=row1, created_time=row[2]) File "C:\Users\myfxhuta\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py" in init … -
Different Permissons using decorators inside ModelViewset methods for "list", "create" , "retrieve", "update"
I want to add different permissions for different methods of ModelViewset class using decorator. I tried class abcd(viewsets.ModelViewSet): @permission_classes(IsAuthenticated,)) def list(self, request, format=None): try: @permission_classes(CustomPermission,)) def create(self, request, format=None): try: But it isn't working. I also tried using @method_decorator. That didn't worked either. I know we can do in the following way: def get_permissions(self): if self.action == 'create': return [IsAuthenticated(), ] return super(abcd, self).get_permissions() But I was wondering if we can achieve this using decorators for Django Rest Framework. -
Exception when processing form request despite 200 status
I'm creating a separate Django REST-api for my ReactJS app. I'm calling a fetch POST API to my endpoint to sign up users. I'm not sure what the error means since I'm getting a status of 200. My Terminal traceback: [30/Jan/2019 10:09:27] "OPTIONS /newuser/ HTTP/1.1" 200 108 Exception happened during processing of request from ('127.0.0.1', 64666) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 651, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 361, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 721, in __init__ self.handle() File "/Users/shiningsunnyday/Documents/GitHub/kvizo_core/web/quizkly_env/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/Users/shiningsunnyday/Documents/GitHub/kvizo_core/web/quizkly_env/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer My ReactJS code: var csrftoken = document.getElementById('token').getAttribute('value'); console.log(csrftoken); fetch('http://localhost:8000/newuser/', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken }, body: JSON.stringify({ username: this.state.username, password: this.state.password, }), }).then( (response) => { console.log("We did it!"); console.log(response.json); } ).catch( (error) => { console.log(error); } ); My Django view code: class SignUp(APIView): parser_classes = (JSONParser,) permission_classes = (AllowAny,) def post(self, request, format = None): print(request.data, " is request data") if 'username' not in request.data or 'password' not in request.data: raise ParseError('Username or password not provided') if … -
How to filter a model and join on User model
I have two models. First one is "User" model in app "accounts", another one is "Records" model in app "activities". I want to show user list with a count of their activities for different actions filtered by date range on "date_and_time" #models.py file in "activities" app from acccounts.models import User class Records(models.Model): class Meta: verbose_name = "Record" verbose_name_plural = "Record" activity_choices = (('Solved', 'Solved'), ('Closed', 'Closed'), ('Escalated', 'Escalated')) user = models.ForeignKey( User, on_delete=models.PROTECT, null=True, blank=True) date_and_time = models.DateTimeField(auto_now=True) activity = models.CharField(max_length=50) url = models.URLField(max_length=255, null=True, blank=True) I expect something will print in my template output like: Name | Solved | Closed | Escalated Hasinoor | 120 | 35 | 9 James | 92 | 32 | 17