Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create APIs for UserProfile with rest framework?
I have created a UserProfile model with OneToOne relationship with User model. The UserProfile model is shown below. from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile_number = models.IntegerField(blank=True, unique=True, null=True) profile_image = models.ImageField(upload_to="media", blank=True ) current_location= models.CharField(max_length=300, unique=False, blank=True) created_at = models.DateTimeField("created at", auto_now_add=True) university = models.CharField(max_length=100, blank=True) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) The serializer class is shown below. from rest_framework import serializers from .models import UserProfile class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ( 'mobile_number', 'current_location' ,'university','profile_image') Iam using token authentication. How can I use the ListCreateViewand other classes to implement the post, put ,get and delete method in the best way possible. I also need to validate these data before saving(like mobile_number length should be 10 and mandatory) -
how can I improve my helpers / models to give me true / false instead of returning me invalid token view?
I am trying to fix this error which works as expected, but however at the moment to send the link confirmation link. I notice it never changes, and my update password view it doesn't seem to be created, and it always will display the form I have if not token Invalid. I am not sure a decent way to fix these errors especially the ### helpers from django.contrib.auth import authenticate, login, get_user_model from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.core.mail import EmailMessage def generate_password_reset_token(request, email): try: user = get_user_model().objects.get(email=email) except get_user_model().DoesNotExist: return False get_user_model().objects.filter(email=user).delete() created = get_user_model().objects.create(email=user, token=user.token) email_subject = 'account recovery code' current_site = get_current_site(request) html_message = render_to_string('email/account-recovery.html', { 'domain': current_site.domain, 'token': user.token }) mail = EmailMessage(email_subject, html_message, to=[email]) mail.content_subtype = "html" created = mail.send() if not created: return False return True def verify_password_token(token): try: token = get_user_model().objects.get(token=token) except (TypeError, ValueError, OverflowError, get_user_model().DoesNotExist): token = None if token is not None: return True else: return False views class ResetPassword(View): def get(self, request): return render(request, 'account/forgot-password.html', { 'form': AuthenticationForm }) def post(self, request): form = RequestRestoreCodeForm(request.POST) if form.is_valid(): if generate_password_reset_token(request, form.cleaned_data.get('email')): return JsonResponse({'message': "Please check your registered email for instructions on recovering your account."}) # valid else: return … -
Methods from a single view to different endpoints: keep APIs for HTML and for JSON separated (Django Rest Framework)
Could you help suggesting how to keep coding style organised to keep endpoints from HTML and JSON separated, in Django Rest Framework ? In Flask I am used to keeps endpoints for serving Json, and ones for serving HTML, separated, like: @application.route('/api/') def api_root(): #... return jsonify({'data' : data}) and @application.route('/home/<string:page>/', endpoint='page_template') #... return render_template(template, page) And so I could serve the APIs like: /api/page => serve the json for the page, say for AJAX etc. /page => serve the corresponding html page In Django RF, I read that a ModelViewSet can serve both. So I could keep everything in one place. However, when I come to map views on the router, I would have all the endpoint served respect the path related my model, they would be all sub-path of /api Could you help in advising a good coding practice to make use of ModelViewSet, and route endpoints for html separated from APIs ? This is the example Im working on, my doubts are in comments: from rest_framework import viewsets from rest_framework import generics from rest_framework.decorators import action from rest_framework.response import Response from .serializers import PersonSerializer from .models import Person class PersonViewSet( viewsets.ModelViewSet): queryset = Person.objects.all().order_by('name') serializer_class = PersonSerializer … -
how to execute a user supplied python script on button click django
I have set up a template in django app. It has two inputs (i.e absolute path of python script and argument) and a button. On button click, I want python script supplied by user in input 1 to be executed with input 2 as argument. Output of that script should then be printed to same html page. -
Django receive a signal when a model value gets changed from a different application or when manually edited in database
I'm currently in a peculiar situation where I am not allowed to use a new database even though the product owner wants a new and improved application. This means that my new application will have to work with the old database. This database doesn't use foreign key constraints, which makes the usage of modules such as Django tables 2 nearly impossible. The solution I thought up is the following: Add in an extra foreign key field to required tables Users in the old app change an id of sorts, let's say team id of a news article Django app sees this change, finds the correct team model and links that team model to the foreign key field What I've tried so far to achieve this: Add in a custom save method to my model. This does work when I change the model with a view or CLI, but doesn't do anything when I manually change a value in the database or use a different application to change any values. class Team(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) intra = models.ForeignKey(Intra, on_delete=models.DO_NOTHING) def save(self, force_insert=False, force_update=False): print("test") The next solution I tried is using a receiver. This again works in CLI … -
my profile object is not getting serialized in the user serializer
I am using Django rest auth to authenticate my users, that works well. how my model is set up is that I have the custom user model for authentication and I also have a profile model that gets created with a signal. I want that when the users are fetched in its URL, the profile for that user is also called an object in user. my models.py (I didnt include some models like the user managers, skill, e.t.c as i felt they werent relevant) class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=254, unique=True) fullname = models.CharField(max_length=250) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['fullname'] objects = UserManager() class Profile(models.Model): ''' Note: profile photo is expecting photos link gotten from cloudnairy from the frontend - The height is calculated in feets and inches - Need to sort out location (lives in) - Need to add an age function - Need to add achievemnet as a foreign field - Need to add education also as a foreign field - Add follow functionality ''' user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, verbose_name="DOB", null=True) bio = models.TextField(max_length=500, blank=True, null=True) … -
Authorization Vk, output a list of friends?
Made authorization Vk with the help django allauth, until that perhaps simply start pressing hard on authorization he will go, but not will display outcome As after authorization see displaying the name of authorized user and 5 any friends user. Also, when Perezhogin to the site authorization does not fly. examples of prompt. -
How to disable 'required' attribute of model's fields only for one form? Django
I have Post model which has such tables as title, body and etc. I want to create form in which this fields won't be required. At the moment, my form looks like this: class CreateUpdatePostForm(forms.ModelForm): class Meta: model = Post fields = ["title", "body"] -
How can I create new 'draft' object with class based UpdateView before form filling?
I have a product model that has a lot of field. When user click to "Create New Product" I want create new object (just create object that it has id, seller, draft status), and show blank form. Because I want to use Ajax asyncronous upload to this object. User fills the object's other fields (like upload images) and save. Also user should be able to edit own draft products on own dashboard. First problem: I used UpdateView, but If I override get_object method and I click "Create New Product", django calls twice this method and create two object?! I want call just one time. Second problem: When users wants to edit draft items, they go to dashboard and edit someone. Should I create new class-based view for this or can I use same view for both operation? Maybe I can add get_or_create method to my get_object method, is It possible? my model: class Product(models.Model): seller = models.ForeignKey("auth.User", on_delete=models.CASCADE, verbose_name="Seller", default=None) category = models.ForeignKey("Category", on_delete=models.CASCADE, verbose_name="Category Name", blank=True, null=True) title = models.CharField(max_length=50, verbose_name="Product Title", blank=True, null=True) status = models.IntegerField(choices=((x.value, x.name.title()) for x in Status), default=Status.TASK) images = models.ManyToManyField("ProductImages", blank=True, null=True) my class-based view: class ProductCreateViewTest(LoginRequiredMixin, UpdateView): template_name = 'product/add.html' form_class = … -
modal popup on hyperlink click in hovertext in plotly
i want to open modal dialog on click of hyperlink in hovertext in PLOTLY PYTHON. i had included hyperlink in data from backend, but when i add class or id to it the graph doesn't myPlot.on('plotly_click', function(data){ var eventid = ''; for(var i=0; i < data.points.length; i++) { ClickIndex = data.points[i].pointIndex; eventid = data.points[i].data.DID[ClickIndex]; } if(eventid) { openFormPopup(eventid) } }); i want to run same function on click of a hyperlink in graph. Show Summary is hyperlink Show summary is hyperlink i have send from backend. i want to fire same function which runs on plotly_click. -
How can i generate pdf from html code and pdf file along with sendgrid API V3 uisng python django
i have a variable which contain the template code like template = ''' <html> <div> Hello world </div> </html> ''' i want to generate a pdf and attach file with the sendgrid code below import os from sendgrid import SendGridAPIClient template = ''' <html> <div> Hello world </div> </html> message = { 'personalizations': [ { 'to': [ { 'email': 'test@example.com' } ], 'subject': 'Sending with Twilio SendGrid is Fun' } ], 'from': { 'email': 'test@example.com' }, 'content': [ { 'type': 'text/plain', 'value': template } ] } try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(str(e)) currently i have created a template of invoice and now i want to know how to generate a pdf with that template and attach that pdf file with the email my template code is too lengthy so im not including it here -
Call function when click function django
I want to call my python function, when user clicked button "submit" on this page http://junjob.ru/accounts/login/ How can I do it? My code: views.py class BBLoginView(LoginView): template_name = 'vacancy_list/login.html' class BBLogoutView(LoginRequiredMixin, LogoutView): template_name = 'vacancy_list/vacancy_list.html' next_page = reverse_lazy('vacancy_list') urls.py urlpatterns = [ path('accounts/login/', BBLoginView.as_view(), name='login'), path('accounts/profile/', profile, name='profile'), path('accounts/logout/', BBLogoutView.as_view(), name='logout'), ... login.html {% block content %} <div class="container" style="margin-top:10px"> <h2>Login</h2> {% if user.is_authenticated %} <p>You are already registered</p> {% else %} <form method="post"> {% csrf_token %} {% bootstrap_form form layout='horizontal' %} <input type="hidden" name="next" value="{{ next }}"> {% buttons submit="Submit" %} {% endbuttons %} </form> {% endif %} </div> {% endblock %} -
Django template rendering HTML elements in the wrong order
This is a Django beginner question (or possibly just an HTML problem). I'm rendering a very simple HTML page with a template (I'll make it look nice later). It has two divs, each containing a header and a table. If I print the rendered content in my view, it looks right, but the HTML delivered to the browser has both headings, then both tables. Template <!doctype html> <html style=\"font-family:Helvetica\> <head> <meta charset="utf-8"> <title>Choir Database</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'css/choirdb.css' %}"> </head> <body> <!-- MAIN TABLE --> <div> <h1>{{ title1 }}</h1> {% if value_list1 %} <table style=\"width:25%;font-family:Helvetica\"> <tr/> {% for valuePair in value_list1 %} <tr><td>{{ valuePair.0 }}</td> <td>{{ valuePair.1 }}</td></tr> {% endfor %} <tr> <td><a href=\"..\">Home</a></td> {% else %} <p>No values found</p> {% endif %} </div> <!-- SECONDARY TABLE --> <div> <h2>{{ title2 }}</h2> {% if value_list2 %} <table style=\"width:25%;font-family:Helvetica\"> <tr/> {% for valuePair in value_list2 %} <tr><td>{{ valuePair.0 }}</td> <td>{{ valuePair.1 }}</td></tr> {% endfor %} <tr> <td><a href=\"..\">Home</a></td> {% else %} <p>No values found</p> {% endif %} </div> </body> </html> View context = { 'title1': 'Liturgy Detail', 'value_list1': nameValuePairsPiece, 'title2': 'Laudate Recommendations', 'value_list2': rec_details, } output = render(request, 'two_tables.html', context) print ("output is " … -
Why my slug related field shows users object(1) instead of suggested field name in Django?
I wrote an app named as credentials. models, serializers and views are : models.py : from django.db import models class Users(models.Model): username = models.CharField(max_length=20, blank=False) inserted_timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('inserted_timestamp',) class UsersDetails(models.Model): user = models.ForeignKey( Users, related_name='id_user_details', on_delete=models.DO_NOTHING, ) user_title = models.CharField(max_length=30, blank=True) user_first_name = models.CharField(max_length=25, blank=True) user_last_name = models.CharField(max_length=40, blank=True) user_birthdate = models.DateField(blank=False) inserted_timestamp = models.DateTimeField(auto_now_add=True) details_creator = models.ForeignKey( Users, related_name='dtlcreator_user_details', on_delete=models.DO_NOTHING, # default=1 ) class Meta: ordering = ('user_id',) class UsersPasswords(models.Model): user = models.ForeignKey( Users, related_name='id_user_password', on_delete=models.DO_NOTHING) salt = models.CharField(max_length=200, blank=True) pwdhash = models.CharField(max_length=200, blank=True) inserted_timestamp = models.DateTimeField(auto_now_add=True) pwd_creator = models.ForeignKey( Users, related_name='pwdcreator_user_details', on_delete=models.DO_NOTHING) class Meta: ordering = ('user_id',) Here is serializers.py : from rest_framework import serializers from credentials.models import Users from credentials.models import UsersDetails from credentials.models import UsersPasswords class UsersSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Users fields = ( 'url', 'pk', 'username', 'inserted_timestamp', ) class UsersDetailsSerializer(serializers.HyperlinkedModelSerializer): user = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username', ) details_creator = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username', ) class Meta: model = UsersDetails fields = ( 'url', 'pk', 'user', 'user_title', 'user_first_name', 'user_last_name', 'user_birthdate', 'inserted_timestamp', 'details_creator' ) class UsersPasswordsSerializer(serializers.HyperlinkedModelSerializer): user = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username' ) pwd_creator = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username' ) class Meta: model = UsersPasswords fields = ( 'pk', 'user', 'salt', 'pwdhash', 'inserted_timestamp', 'pwd_creator' ) … -
Django REST framework adding multiple default objects
I am creating an app for my School which lets you add Teachers/Subjects/lessons...basic school life managing app...I want to give the user a list of the most basic/common subjects. I know that you can assign a default value in Django Models... but that would only create one Object with all the subjects in it... Is there a way to create multiple default object when a new user is created ? Thanks in advance django==2.2 djangorestframework==3.9.2 note : the user should be able to edit the subject list later. -
Build Firebase google signin in Django
I am looking to integrate firebase auth google sign in with Django. But I am not getting a clear picture of how can I achieve it. As Pyrebase has an attribute sign_in_with_email_and_password but not any for Google SignIn. How will view and template be designed? -
django: adding custom permissions stopped working
I have a django project with multiple apps. In one of the apps when I add custom permissions to any model and run makemigration, the migration-file to add the permission is created. When I apply the migration I get no error messages but the permission isn't added to the auth_permission table. class Meta: app_label = 'my_app' permissions = ( ('test_perm', 'Testing'), ) I have tried doing the same in other apps and that works. I have also tried adding a column to the current app and that works as well. Anyone got any idea what it could be? I am running django 1.11.26 -
Pycharm identifies new Django test file as a unittest, not a django test
How do I tell pycharm that the new test file I created is a django test file, and not a unittest file? I have pycharm setup with a django project. I can run all django tests as django tests with the test runner. I created a new test file, wrote a simple unittest on it. The tests run fine with manage.py and with the run configuration for running all tests. But, when I try to run an individual test within the new test file from pycharm it fails because pycharm is trying to run it as a unittest instead of a django test. As shown in the screenshots below, pycharm considers this new file a unittest file, not a django test file. Yet both files are in the same directory, both implement a class that extends Unittest, and both have tests. -
display data in html from django
I tried to display the data (the result return back from upload_file in views.py) in HTML from django, but it didn't show anything after clicking submit button, only jump back to the initial ui. undex.html <!DOCTYPE html> <head> <title>Detect Pothole</title> </head> <body> <p>upload image</p> <form method="post" enctype="multipart/form-data">{% csrf_token %} <input type="file" name="img" accept="image/*" onchange="loadFile(event)"></input> <img id="output"/> <script> <!--view selected image --> var loadFile = function(event) { var output = document.getElementById('output'); output.src = URL.createObjectURL(event.target.files[0]); }; </script> <input method='POST' type="Submit" name="submit" value="submut"></input> </form> {% if submitbutton == "Submit" %} {% for res in result %} {{res}} {% endfor %} {% endif %} </body> </html> view.py def upload_file(request): submitbutton= request.POST.get("submit") if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['img']) result=process('a.png') ## will return 0 or 1 print(result) context= {'form': form, 'submitbutton': submitbutton,'result':result} return render(request, 'index.html', context) else: form = UploadFileForm() return render(request, 'ui.html', {'form': form}) -
How to send mass emails using Django EmailMultiAlternatives
I want to send mass email using Django EmailMultiAlternatives because I am using an HTML email to send as newsletters and send_mass_mail does not support. Below code working fine and sends email only first recipients form the list but I have multiple recipients in the list. Here is my code: def send_birthday_email(): today = date.today() get_dob_email = CoWorker_Data.objects.filter(dob__day=today.day, dob__month=today.month).values('email') mailtosend = "" for mail in get_dob_email: mailtosend = mail["email"] + "," + mailtosend threading.Timer(120, send_birthday_email).start() # Send email subject = 'Happy Birthday from LaunchPad7' from_email = settings.EMAIL_HOST_USER to_email = mailtosend print('Hellll:', mailtosend) with open(settings.BASE_DIR + '/lp7ms/templates/emails/birthday_email.txt') as f: text_message = f.read() message = EmailMultiAlternatives(subject=subject, body=text_message, from_email=from_email, to=[to_email]) html_content = get_template('emails/birthday_email.html').render() message.attach_alternative(html_content, 'text/html') message.send() send_birthday_email() -
what is haystack ,elastic search, elasticsearch_dsl in django?
can anyone explain what is : 1. haystack 2. elastic search 3. elasticsearch_dsl what is the purpose to use this in Django project. i tried to learn in websites but i cannot understand the usage purpose. -
Django debug False prevents access to files saved in media folder
I have a model that takes a File Field which is uploaded in Django admin. I noticed that the files save in the proper folder. But when Debug is set to False, I cannot access the file from the admin area or from the front end user interface. I get an error message that says "The resource could not be found on the server." The app is hosted on Heroku and does the same thing in localhost and live. I read in another post that Whitenoise would work with Heroku but it hasn't resolved the issue. Could someone please point me in the right direction to a fix? The relevant files are below. models.py from django.core.files.storage import FileSystemStorage from django.db import models class DataSet(models.Model): title = models.CharField(max_length=255) date_added = models.DateField(auto_now=True) file_size = models.CharField(max_length=20) file_type = models.CharField(max_length=20) data_file = models.FileField(upload_to='delivery/') def __str__(self): return self.title settings.py import os import django_heroku import dj_database_url BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = Redacted # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False DEBUG_PROPAGATE_EXCEPTIONS = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', … -
Filtering without submit button (Django)
I filter objects by choose one in dropdown box and click submit button, then it will work. But I don't want to click submit button. I need it work immediately after I click on alternative in dropdown box. <form method="GET" class="form-inline"> <select name="filtering" class="form-control"> <option value="none">Alt 1</option> <option value="01">Alt 2</option> <option value="02">Alt 3</option> </select> <input type="submit" value="Filter"> </form> PS. I use html with python+django. -
Register multiple routes in Django DRF - using and calling methods in ModelViewSets or Generics
I want to understand how to use Django DRF to register: two different endpoints, and only one endpoint making use of custom fields Please show the differences in using ViewSets and Generics. These are my attempts. I came from Flask, and found very clear to define multiple end-points with decorators. Flask - example endpoints to get a list of objects,last object option 1 @application.route('/people/', endpoint='people') def people(): # return a list of people pass @application.route('/last/', endpoint='last_person') def last_person(): # return last person pass option 2 @application.route('/people/', endpoint='people') def people(): field = request.args.get('last', None) if field: # return last person from list of people else: # return list of people I understood the benefit of DRF may be consistency and read the documentation, but found cumbersome and wish to understand more clearly how to make use of ModelsViewSets and Generics to see the benefits VS flask. Please help with an example to fetch a list of users, and last user. Django DRF - first approach (ModelViewSet) # serializer.py from rest_framework import serializers from .models import Person class PersonSerializer( serializers.HyperlinkedModelSerializer): class Meta: model = Person fields = ('name', 'nickname', 'timestamp') # views.py class PersonViewSet( viewsets.ModelViewSet): queryset = Person.objects.all().order_by('name') serializer_class = PersonSerializer I … -
django form input range how to show value?
I have a question about range input in Django 2. How can I display the current value of the input range slider? Now its only slider without any values. Maby I should save value every time it changes, but I'm looking for simplicity. Form: scale = forms.IntegerField(widget=forms.NumberInput(attrs={'type':'range', 'step': '5', 'min': '-100', 'max': '100'}), required=False) Template: {{form.scale}} this how it looks like