Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sending mail on post_save django
I want to send mail when I create entry in database, I'm using django post_save signal for that, but I'm failing in doing that, I'm not sure what I'm I missing here, is there a change that someone can help me understand what is happening. I'm using postmarker for the email configuration. model.py class Winner(BaseModel): name = models.CharField(max_length=225, blank=True, null=True) email = models.EmailField(unique=True, db_index=True) telephone = models.CharField(max_length=225, blank=True, null=True) postal_code = models.CharField(max_length=225, blank=True, null=True) reseller_code = models.CharField(max_length=225, blank=True, null=True) company_contact = models.CharField(max_length=225, blank=True, null=True) company_name = models.CharField(max_length=225, blank=True, null=True) company_telephone = models.CharField(max_length=225, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, db_index=True) EMAIL_FIELD = 'email' class Meta: verbose_name = 'winner' verbose_name_plural = 'winners' def get_email(self): """ Return the indentifying email for this Winner """ return getattr(self, self.EMAIL_FIELD) def __str__(self): return self.get_email() signal.py def send_winner_info(sender, instance, created, **kwargs): winner = instance if created: winner_dict = { "Name: ", winner.name, "Email: ", winner.email, "Telephone: ", winner.telephone, "Postal Code: ", winner.postal_code, "Reseller Contact: ", winner.reseller_contact, "Company Name: ", winner.company_name, "Company Telephone: ", winner.company_telephone, } message = render_to_string('mails/winner.html', winner_dict) subject = "Giveaway Winner Information" from_email = settings.DEFAULT_FROM_EMAIL recipients_list = settings.DEFAULT_RECIPIENT_LIST send_mail(subject, message, from_email, recipient_list=recipients_list) post_save.connect(send_winner_info, sender=Winner) -
Stripe ID saves to a new row in Django AbstractUser table
I was able to successfully complete a test subscription payment through Stripe. However, when I checked my Postgresql user database table, I found that during the checkout and Stripe customer creation process, the StripeID and Stripe_subscription_id were saved to a new user. The desired behavior is for these two pieces of data to be added to the current logged-in user's profile. I am using a custom AbstractUser model and suspect the issue lies there. I appreciate a point in the right direction to fixing this. My relevant code snippets are below: models.py # users/models.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass # add additional fields in here stripeid = models.CharField(max_length=255) stripe_subscription_id = models.CharField(max_length=255) forms.py # users/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('username', 'email') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = UserChangeForm.Meta.fields admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): model = CustomUser add_form = CustomUserCreationForm form = CustomUserChangeForm admin.site.register(CustomUser, CustomUserAdmin) views.py # pages/views.py import os from django.shortcuts import render, get_object_or_404, redirect … -
Are named URLs in Django really necessary?
The URL mappings I used in my Django applications are "named URLs" as follows (according to Django's documents). For example, in the project's urls.py: path('main/', include('main.urls', namespace='main')), and in the main app's urls.py: path('', views.main, name='main'), With the above namespace and name settings, the following formats may be used in views and templates, respectively: reverse('main:main') {% url 'main:main' %} One of the advantages of using named URLs is that we may easily change the URL mappings without affecting the codes in views or templates. I have developed dozens of real business Django projects. The above may sound reasonable, but I have never changed the URL settings in any of my projects. I wondered what kinds of projects will change the URL mappings from time to time so the named URLs are useful? -
Django automatic login after signup
I'm trying to get users automatically logged in after registration. However the user only seems to be logged in for the duration of rendering the next html page (user.is_authenticated returns True in my templates) and gets logged out immediatly after (request.user returns AnonymousUser in a method I call via AJAX on the next page - moving to another page also makes clear you are not logged in anymore since my templates render the login instead of the logout links again). If I try the commented code instead authenticate() always returns NONE. What am I doing wrong? def signup_view(request): if request.method == 'POST': form = UserSignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) send_confirmation_email(user, current_site.domain) # user_login = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1']) # login(request, user_login) login(request, user, backend='django.contrib.auth.backends.ModelBackend') args = {'user': user} return render(request, 'accounts/signup_success.html', args) else: form = UserSignUpForm() args = {'form': form, 'project_name': settings.PROJECT_NAME} return render(request, 'accounts/signup.html', args) -
AttributeError: 'SendGridAPIClient' object has no attribute 'send'
I am using sendgrid to send mail via django, however, it keeps saying AttributeError: 'SendGridAPIClient' object has no attribute 'send' Steps to Reproduce install sendgrid pip install sendgrid run script from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail sg = SendGridAPIClient("the_api_key") email_data = Mail( from_email="support@email.africa", to_email="example@email.com", subject="YOUR EVENT IS NOW LIVE ON SITE!", ) email_data.dynamic_template_data = json.dumps({ "username": "example username", "item_name": "example item name", "item_slug": "path to example item slug", "template_id": "transactional template id", "message_type": "EMAIL" }) response = sg.send(request_body=email_data.get()) error: Traceback (most recent call last): File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/viewsets.py", line 116, in view return self.dispatch(request, *args, **kwargs) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/mixins.py", line 84, in partial_update return self.update(request, *args, **kwargs) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/mixins.py", line 70, in update self.perform_update(serializer) File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/mixins.py", line 80, in perform_update serializer.save() File "/Users/Retina15/project/virtual/lib/python3.6/site-packages/rest_framework/serializers.py", line 209, in save self.instance = self.update(self.instance, validated_data) File "/Users/Retina15/project/store/serializers/event.py", line 358, … -
How can I access foreign keys in Django?
guys! I have the following code: class Model3D(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) description = models.CharField(max_length=500) original_Model = models.ForeignKey('Model3D', on_delete=models.CASCADE, null=True) creation_Date = models.DateTimeField(auto_now=True) stl_File = models.FileField(null=True, upload_to='models/stlFiles') scad_File = models.FileField(null=True, upload_to='models/scadFiles') parameter_id = models.ForeignKey('Parameter', on_delete=models.CASCADE, null=True) part_of = models.ForeignKey('Model3D', related_name="part_of_model3d", on_delete=models.CASCADE, null=True) picture_of_model = models.ForeignKey('Pictures', on_delete=models.CASCADE, null=True) class Pictures(models.Model): id = models.AutoField(primary_key=True) picture = models.ImageField(upload_to='models/pictures', null=True) model_id = models.ForeignKey('Model3D', on_delete=models.CASCADE) As you can see Model3D has a foreign key relationship to itself because a 3DModel can consist of a e.g. three other 3DModel parts. Therefore the field 'part of' which references Model3D again. Every Model3D objects has pictures in the Pictures class. My questions: How do I get an Model3D object with all of its part Models? How do I get all pictures of an Model3D object and all pictures of its part Models? I tried so many things regarding select_related but it does not really work. Thank you for your kind help! -
Django: Populate model with CountryField
I have a model which has a CountryField and I want to populate this model from a csv with data. How I set a value for the CountryField? -
Problem with django.db.utils.OperationalError: no such table: main.auth_user__old
I was trying to follow the tutorial https://github.com/stacklens/django_blog_tutorial of building a blog using Django. (The tutorial is written in Chinese, but I think the problem is about the model) When I setup superuser and trying to add my first article to the database as an admin. This error "django.db.utils.OperationalError: no such table: main.auth_user__old" occur. I looked up the similar question on the overflow, it seems that the problem is solved by upgrading Django version to 2.1.5. However, I'm using Django 2.2.7 which is the most recent version and still get the same error. I have tried downgrade the version to 2.1.5 but it still not working. -
Securing third party API keys of User while using them with my app
I am making a django app that needs 3rd party keys of user to fetch data periodicaly from different api and store in the app. How can I achive this without seeing or accessing the users API keys. If not how can I assure/convince them that I will never use or see their API key? -
How to integrate Tally ERP-9 with Python
How to integrate Tally ERP-9 with Python(Django) for Pushing and pulling amount based on ledger. -
Best implementation follow and unfollow in django rest framework
Trying to implement a following and followers and feature in Django-rest, if I were to create this not using rest framework, I have an idea how this can be done. But this time I have little to no idea how this can be done. Please: 1) What is the best way to do something like this assuming I am working on a big project? 2) I am majorly lost at what to do at the serializer and view section, I just know that that in the serializer part I select the following model alone Assuming I have a profile model like this class Profile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followers', blank=True) other content……. Please any help is appreciated -
Authentication credentials error in react app
I have a react app which uses a Django Rest Framework as backend. When I run both DRF as well as React app on local machine it works perfectly. But When I use the Amazon deployed version of the DRF, it does not let me sign-in in the react app Here's the settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ] } CORS_ORIGIN_ALLOW_ALL = True What is it that I am doing wrong? How can I use the live version of my backend with the local Frontend ? -
How to use Augmented Reality video developed using unity in Django (python)?
I created an Augmented reality video using unity. I want to use that video to write backend in django(python). Can anyone tell me how to import AR video developed in Unity to Django framework ? -
How can i run a project after clonning from github?
I want to run a specific project after downloading it from Github. I read all the instructions also but i didn't understand how to run it with my existing interpreter. I have installed all the required packages also. Please help someone and please don't flag my comment as useless. Django Job Portal -
How to change/mark a color of the roads in map? (FYI: I'm using Django framework)
Please help I'm using Django as a framework. It will be more helpful if we mark according to longitude and Latitude. -
Django: Attribute error 'Signage' object has no attribute subscription_id?
I have the following model: class Signage(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) subscription_plan = models.CharField('subscription_plan', default='', blank=True, max_length=255) subscription_id = models.TextField('subscription_id', default='', blank=True) transaction_id = models.TextField('transaction_id', default='', blank=True) def __str__(self): return self.id Here is the serializer: class SignageSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Signage fields = ('id', 'user', 'subscription_plan', 'subscription_id', 'transaction_id') read_only_fields = ('id', ) class CreateSignageSerializer(serializers.ModelSerializer): def create(self, validated_data): signage = Signage.objects.create(**validated_data) return signage def update(self, instance, validated_data): instance.subscription_plan = validated_data.get('subscription_plan', instance.subscription_plan) instance.subscription_id = validated_data.get('subscription_id', instance.susbcription_id) instance.transaction_id = validated_data.get('transaction_id', instance.transaction_id) instance.user = validated_data.get('user', instance.user) instance.save() return instance class Meta: model = Signage fields = ('id', 'user', 'subscription_plan', 'subscription_id', 'transaction_id' ) read_only_fields = ('id',) Here is the view: @api_view(['GET', 'POST']) def createSubscription(request): client = razorpay.Client(auth=("rzp_test_BmzgkoO2Is1glp", "oHmTJUCrdw2mP39BCrZdTY0t")) if request.method == 'GET': subscription_id = request.GET.get("subscription_id", None) if subscription_id is not None: return Response(client.subscripton.fetch(subscription_id)) else: return Response(client.subscription.all()) else: subscription = client.subscription.create(data={ "plan_id": request.data["plan_id"], "total_count": request.data["total_count"] }) signage = Signage.objects.get(id=request.data["signage_id"]) payload = { "subscription_plan": request.data["plan_id"], "subscription_id": subscription["id"] } updated_signage = CreateSignageSerializer(signage, data=payload, partial=True) if updated_signage.is_valid(): updated_signage.save() else: return Response(updated_signage.errors, status=status.HTTP_400_BAD_REQUEST) return Response(subscription, status=status.HTTP_200_OK) This is the error I get: AttributeError at /api/v1/subscriptions/ 'Signage' object has no attribute 'susbcription_id' In the database the rows do not have any … -
Django: How to raise Http401 and Http403 exceptions like Http404, RAISE EXCEPTION not RESPONSE
I'm trying to make an api using Django, and i'm verifying the request header if it contains an api key and raise an exception according to that, like so: def _check_driver_authorization(request): if request.headers.get('authorization') is not None: token = request.headers['authorization'] user = Driver.objects.filter(access_token=token) if user.exists(): return raise Http401 else: raise Http403 I didn't find anyone trying to make it like this, and i've searched many threads in here, they are all trying to return responses (render), my case i'm trying to interupt the request and raise the exception. I inspired this from get_object_or_404. -
Unable to configure web server (tried nginx, apache, gunicorn) with sokcet.io for a django application
I have a Django Application using python-socketio for communicating internally with other apps in my project. I am not able to use Django signals due to some constraints in the project. When I try to configure the web server for my application, the SocketIO throws an error when binding the application to the SocketIO. The Django Application is able to run when commented out the binding of the application. I am using 'threading' method for the socket communication. I have also tried it with 'eventlet' method in uwsgi when trying to connect with gunicorn. I have given a good research regarding the same but unable to figure out where I have gone wrong. I have given the wsgi.py file for your reference. import os import socketio from django.core.wsgi import get_wsgi_application from socket_app.views import sio from socket_app import client.socket_connection as client from socket_app.client import * os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") django_app = get_wsgi_application() application = socketio.WSGIApp(sio, django_app) -
How to view API data within a GET method that's created using POST method in Django (without a model)?
I have created a DRF API that allows me to submit an image using the POST method via POSTMAN. The image is not stored in the model. After it's submission, I want to view the image's name in the browser using the Django Rest Framework. After reading sources in the net, I found out that people used the GET method in order to view all the data in a model. However, I don't have a model (don't require it for now) so how can I implement this requirement? The result should be something like this: { "image_name": <"name_of_the_image_stored"> } This is what I had done so far: from rest_framework.views import APIView from rest_framework.response import Response from .serializers import ImgSerializer from rest_framework import status from rest_framework.parsers import FileUploadParser class ImageAPI(APIView): def post(self, request): parser_classes = (FileUploadParser,) #key is 'image' when uploading in POSTMAN file = request.data.get('image', None) if file: uploaded_file = file fs = FileSystemStorage(location=settings.PRIVATE_STORAGE_ROOT) filename = fs.save(uploaded_file.name, uploaded_file) data = [{"image_name": filename}] serializer = ImgSerializer(data, many = True).data return Response(serializer, status = 200) else: return Response("Please upload an image", status = 400) def get(self, request): #What should I do here in order to view the submitted image above? serializers.py: from … -
How To Set Up a Error log and Access Log in python for Ubuntu 18.04 digital ocean server
i am new in Ubuntu 18.04 digital ocean server and Python. If any way to Create Error log and access log on my Ubuntu 18.04 digital ocean server? can anyone help me? -
How to provide different serializers based on incoming request
I am trying to provide different serializers based on incoming request for my categoryname Field in my model Role. Here is what i have tried: def get_serializer_class(self): categoryname = Role.objects.filter(categoryname=categoryname, pk=pk1, owner=owner) if self.request.method == 'GET' and self.request.user.has_perm('user.view_user'): return RoleSerializerDepth if self.request.method == 'PUT' and 'Developer' in categoryname: return RoleSerializerDeveloper if self.request.method == 'PUT' and 'Investor' in categoryname: return RoleSerializerInvestor if self.request.method == 'PUT' and 'Auditor' in categoryname: return RoleSerializerAuditor if self.request.method == 'PUT' and 'Educational' in categoryname: return RoleSerializerEducationalInstitution return RoleSerializerBasic Here is my model class Role(models.Model): address1 = models.TextField(name="address1", max_length=150, null=True) address2 = models.TextField(name="address2", max_length=150, null=True) vat = models.CharField( max_length=100, null=True) categoryname = models.CharField(max_length = 100, blank=True, db_index=True) date_created = models.DateField(null=True) is_active = models.BooleanField(null=True) is_passive = models.BooleanField(null=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='roles', on_delete=models.CASCADE) And my serializers from rest_framework import serializers from .models import Role from core.serializers import DynamicFieldsModelSerializer, BasicSerializer from user.serializers import CustomUserSimpleSerializer from rest_framework.validators import UniqueTogetherValidator class RoleSerializerBasic(DynamicFieldsModelSerializer ,BasicSerializer,): owner = serializers.ReadOnlyField(source='owner.username') # class Meta(BasicSerializer.Meta): model = Role # Model to serialize fields = ('address1', 'address2','vat','categoryname','date_created', 'owner') extra_kwargs = { 'categoryname': { 'validators': [] } } def update(self, instance, validated_data): address1 = validated_data.pop['address1'] address2 = validate_data.pop['address2'] categoryname = validated_data.pop('categoryname') vat = validated_data.pop('vat') date_created = validated_data.pop('date_created') instance.save() return instance … -
Django SplitDateTime widget throws 'list' object has no attribute 'strip'
I am trying to create event with start date-time and end date-time with django. In the forms I've tried to seperate the date and time inputs with AdminSPlitDateTime widget (I'd like to have some JS for the input.) When I tried to create an event django gives me "'list' object has no attribute 'strip'" error. Also happens with SplitDateTimeWidget. When I removed the widget or use DateTimeInput widget (no split) everything works as expected. But User can confuse to enter the proper format for date time. SO I want to user AdminSplitDateTime. It must be something with spliting the date and time with widgets but I couldn't figure a way to solve this. Using Python 3.7 django 2.2.7 pipenv 2018.11.26 my Model is class Event(models.Model): event_start = models.DateTimeField() event_end = models.DateTimeField() notes = models.CharField(max_length=140, null=True, blank=True) hasta = models.ForeignKey(Hasta, on_delete=models.CASCADE) doktor = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'{self.event_start} -- {self.event_end}' class Meta: ordering = ['event_start'] my Form class is: class EventCreateForm(ModelForm): event_start = forms.DateTimeField(widget= admin_widgets.AdminSplitDateTime()) event_end = forms.DateTimeField(widget=admin_widgets.AdminSplitDateTime()) def __init__(self, *args, **kwargs): """this whole thing is for filtering the hasta objects. User can only create an event with his patients.""" self.user = kwargs.pop('user') super().__init__(*args, **kwargs) self.fields['hasta'].queryset = Hasta.objects.filter(doktor_id=self.user.id) class Meta: … -
Best index for a Django model when filtering on one field and ordering on another field
I use Django 2.2 linked to PostgreSQL and would like to optimise my database queries. Given the following simplified model: class Person(model.Models): name = models.CharField() age = models.Integerfield() on which I have to do the following query, say, Person.objects.filter(age__gt=20, age__lt=30).order_by('name') What would be the best way to define the index in the model Meta field? Which of these four options would be best? class Meta indexes = [models.Index(fields=['age','name']), models.Index(fields=['name','age']), models.Index(fields=['name']), models.Index(fields=['age'])] Thank you. -
Read sqlite from request body in Django
I want to read the sqlite database from request body without saving it into temporary file. The request has been sent by: curl -X POST --data-binary @mydb.sqlite3 -H "Content-Type: application/octet-stream" "http://localhost:8000/upload_sqlite" My view function like this: def upload_sqlite(request): print(request.body.decode('utf-8')) conn = sqlite3.connect(request.body) cursor = conn.cursor() cursor.execute("SELECT * FROM table") # do something cursor.close() conn.close() return HttpResponse(status=200) And the console output is here: b'SQLite format 3\x00\x04\x00\x01\x01\x00@ \x00\x00\x00\x18\x00\x00\x00\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x0...' ...ignored... File "/path/to/views.py", line 208, in upload_sqlite conn = sqlite3.connect(request.body) ValueError: embedded null byte -
What are the cons of using mysql's reserved keywords as fields with django?
I have a Django model as: Class DataFile(models.Model): file = models.FileField(upload_to=get_file_upload_path) But, file is a reserved keyword in MySQL. I know that we can use any reserved keyword as column name by wrapping it in ``. My senior advised me not to use reserved keywords and use something which is nearly meaningful other than just file. What are the cons?