Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Possibly empty Foreign Key in forms.py leads to not null constraint fail
I have a class customer, that holds some information, for example a contact person for this customer. This field can be empty and the model shows simplified as follows: model: class Customer(models.Model): name = models.CharField('Company name', max_length=120) contact_persons = models.ForeignKey(ContactPerson, blank=True, null=True, on_delete=models.CASCADE) The corresponding view: class CustomerCreateView(CreateView): model = Customer template_name ="gap/add_customer.html" form_class = CustomerModelForm success_url = reverse_lazy('customer-list') And the form: class CustomerModelForm(ModelForm): required_css_class = "required" class Meta: model = Customer fields = "__all__" Now, when I enter the data I always end up in a NOT NULL constraint failed: gap_customer.contact_persons_id. How would I solve this? -
What will happen if I migrate django models directly from the mysql databse
Earlier i had this as my model class. class Certificate(models.Model): User = models.AutoField(primary_key=True) but after few months i added "data field" into my model class directly from the sql and without using migrations. Now i am just wordering if i change the code in my models and again make migrations, will it work? class Certificate(models.Model): User = models.AutoField(primary_key=True) data = models.TextField(null=True, blank=True) Can anyone suggest me? -
How to mark a special group from the set of groups to which a user belongs?
I would like to add a field in a custom User model indicating the role, which the user currently holds, i.e. mark the group from the set of groups to which the user belongs. One way to do that is to add to User a FK referring to Group, like this: from django.contrib.auth.models import AbstractUser class User(AbstractUser): current_role = models.ForeignKey(Group, verbose_name="Current role", blank=True, null=True, on_delete=models.SET_NULL) However, this means that the data consistency has to be preserved with some additional coding, e.g. in case the current role of the user is removed from the set of groups (roles) he belongs. In order to avoid this, maybe the foreign key could refer to the intermediate table auth_user_groups, instead of Group. Is this a valid option or is there another smart way to solve this issue? -
how to open a folder got as response from a website
I sent Post data to a server and it returned me something.I stored the response in "responsedata" like this responsedata = requests.post(url,data=payload) to know what has been returned i did print(responsedata,responsedata.content) the output in cmd prompt was <Response 200> b'charts/chart.xyz.png' now it looks like the website returned me an image (.png) but its probably in the "charts/" folder.what should i do to save the image to my database(django).(I dont know what tags to use for this,so I have put the lang and package i am using) -
How to get account confirmation key from django email
I have spent days on this so thanks in advance for anyone that can help! I am testing Django AllAuth and need to test the account confirmation link. It contains a key generated by EmailConfirmationHMAC at the end of a link, a la: "thanks for registering! click here to activate: http:/site/confirm/1093840493 I need to be able to extract the 1093840493 part so that I can test it. This question asked for something similar: How to test email confirmation? But my django.core.mail has no 'outbox'. I'm using Django 2.2 and Python 3.6 I can generate a new confirmation but I hope to be able to capture the confirmation as it is initially sent out upon registration. Thanks again for your help. -
Cannot connect to redis://:**@redis:6379//: AUTH <password> called without any password configured for the default user
I have a Django project that works with Celery. The problem is that when I run celery with supervisor, it cannot connect to redis. The project is built using Docker. This is my code: settings.py : CELERY_BROKER_URL = 'redis://:%s@%s:%s' % \ ('foobared', os.environ.get('redishostname', 'localhost'), os.environ.get('redisport', 6379)) CELERY_RESULT_BACKEND = 'redis://:%s@%s:%s' % \ (os.environ.get('redispassword', 'foobared'), os.environ.get('redishostname', 'localhost'), os.environ.get('redisport', 6379)) CELERY_RESULT_PASSWORD = os.environ.get('redispassword', 'foobared') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE CELERYD_USER = "celery" CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' docker-compose.yml: version: '2' networks: app-tier: driver: bridge services: web: build: ./ command: bash -c "python manage.py makemigrations && python manage.py migrate && tail -f /dev/null" ports: - "${webport}:8000" env_file: - ./.env networks: - app-tier redis: image: 'bitnami/redis:latest' environment: - ALLOW_EMPTY_PASSWORD=yes networks: - app-tier When I open the CLI of web container and run suoervisor, it executes following file celeryd_start.sh: NAME="orion-amr" && cd .. && DJANGO_SETTINGS_MODULE=orion-amr.settings && exec celery -A $NAME worker -l INFO So, Celery doesn't exit but in logs file there are following errors: [2020-07-29 06:32:27,085: ERROR/MainProcess] consumer: Cannot connect to redis://:**@redis:6379//: AUTH <password> called without any password configured for the default user. Are you sure your configuration is correct?. Trying again in 32.00 seconds... -
Heroku-Django: App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz
Enumerating objects: 261, done. Counting objects: 100% (261/261), done. Delta compression using up to 4 threads Compressing objects: 100% (243/243), done. Writing objects: 100% (261/261), 5.48 MiB | 251.00 KiB/s, done. Total 261 (delta 54), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to newtonnation. remote: To https://git.heroku.com/newtonnation.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/newtonnation.git' I don't know why am i getting this error, I've tried adding buildpack (heroku/django) still no change. Please Help me. I am using heroku for first time -
Does django render send data to browser using GET or POST?
I am not quite sure how the Django render and HttpResponse actually works. I am sending information to the django view using ajax GET. But i don't really know how the server responds when using render. My ajax code is below:- function get_form_data(){ var url = $("#id_get_form_data_url").val(); var company = $("#id_supplier").val(); if(company){ $.ajax({ url:url, datatype: 'json', data: { 'company':company }, success: function(data){ // $("#id_get_form_data_url").val(); $("#id_sale_order_form").html(data); $("#id_supplier").prop('required',false); // console.log(data); } }) } } the view function below simply filters values of sale_order form field based on the selection of company form field which i pass to the function in ajax GET request. def GetFormData(request): if request.GET.get('company') == "": data = 0 form = SaleOrderInvoiceForm() return render(request,'saleorderinvoicesapp/_form_saleorderinvoice.html',{'form':form}) company_id = request.GET.get('company') sale_order_list = SaleOrder.objects.filter(supplier__id=company_id) form = SaleOrderInvoiceForm() form.fields['sale_order'].queryset = sale_order_list form.fields['supplier'].initial = company_id print(request.method)# this prints GET return render(request,'saleorderinvoicesapp/_form_saleorderinvoice1.html',{'form':form}) As per my understanding, the same request method is used in the render function which in this example is GET What i need to know is, if it is possible to change this request method to POST in view and then send the data to the client in a POST, and which is a preferred method to use if i need to send back … -
Automatically add order to the right customer in Django
I am trying to learn Django by making a database for a fictional dog kennel. One thing I don't understand is how I can automatically add a animal to a customer. What I mean by this is that when I go to my customer page (dynamic) I made a button to a form called AnimalsForm. In this form I have to select a customer again. I was wondering how I could make the form so that it automatically takes the customer from which page I entered the form. [My forms.py][1] [My models.py][2] [My animal form][3] [The button in the customer page][4] [The createanimal view][5] [My urls.py][6] [1]: https://i.stack.imgur.com/kbwR6.png [2]: https://i.stack.imgur.com/FeoZo.png [3]: https://i.stack.imgur.com/R6vU3.png [4]: https://i.stack.imgur.com/PfC6f.png [5]: https://i.stack.imgur.com/CDsRm.png [6]: https://i.stack.imgur.com/9sIJo.png Thanks for the help in advance! -
Why does the foreignkey show up as a dropdown box?
Hi Just wondering why when I try to include a foreign key in my model it shows up as a dropdown box rather than a textbox? Here is my models.py class VolunteerApplication(models.Model): volunteer_name = models.ForeignKey(VolunteerProfile, on_delete=models.PROTECT) phone_number = models.CharField(max_length=10)` This is what it shows up as on the website https://i.stack.imgur.com/bFd0V.png -
Django forms not validate, clean_data is empty, but queryDict is full, how to fix?
Django forms not accept my passed paramets, trying display clean data it nothing, also form i paste not like {{ form }}, just as is, cause it's imposible to convert to neded form, nut i set id the same as in {{ form }} fields. form <form id="fileRenderForm" class="translate__form" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="from-to-section"> <div class="form-dropdown"> <span class="">From</span> <div class="custom-select"> <span id="id_fromLanguage" data-value="0" class="selected-value">Search...</span> <div class="custom-search-select__wrapper"> <div class="custom-search-select"> <input type="text" class="search-select" id="myInput" onkeyup="searchFilter(this);" placeholder="Search for lang.."> <ul class="custom-select__items"> <li data-value="1">Search...</li> <li data-value="3">English</li> </ul> </div> </div> </div> </div> <button class="switch-text"></button> <div class="form-dropdown"> <span class="">To</span> <div class="custom-select"> <span data-value="0" id="id_toLanguage" class="selected-value">Search...</span> <div class="custom-search-select__wrapper"> <div class="custom-search-select"> <input type="text" class="search-select" id="myInput" onkeyup="searchFilter(this);" placeholder="Search for lang.."> <ul class="custom-select__items"> <li data-value="1">Search...</li> <li data-value="3">English</li> </ul> </div> </div> </div> </div> </div> <div class="additional-wrapper"> <div class="file-worker"> <input type="file" name="uploads" id="id_fileToRender" accept="image/jpeg,image/png,image/jpg,application/msword,application/plain,text/plain,application/excel," class="inputfile"> <label for="id_fileToRender" class="file-label"> <span>Upload file for calculation</span> <span class="file-add-block"> <div class="file-bar"> <span class="choosen_file">doc, docx, xls, pdf, jpeg, png</span> </div> <button class="add-file-notification"></button> </span> </label> </div> <div id="captcha-box" class="captcha-box"></div> <button class="calculate-btn upload-dtn" type="submit">Upload</button> </div> </form> this is view from django.conf import settings from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.csrf import csrf_protect # Create your views here. from .forms import renderFileForm from .services.services import * … -
'>' not supported between instances of 'int' and 'NoneType'. form.is_valid
I have error when try to create or update Category model. When I try save or edit with debuger this error does not arise and model saved. views.py def create(request): model = Category() if request.method == 'POST': form = CategoryForm(request.POST, instance=model) if form.is_valid(): form.save() return HttpResponseRedirect('/cabinet/category/') else: form = CategoryForm(instance=model) return render(request, 'cabinet/category/create.html', {'form': form}) form.py class CategoryForm(forms.ModelForm): name = forms.CharField(widget=TextInputCustom()) class Meta: model = Category fields = ['name'] models.py class Category(models.Model): name = models.CharField(unique=True) def __str__(self): return self.name -
Google Flexible App Engine 502 Server Error for Django app
I've hosted my Django app using Google's Flexible app engine custom runtime. It was working fine the last I checked & then I open the website now & I am getting 502 Server Error. It is not showing in the logs also.I'm attaching the screenshots of the HTML error, Logs, App Engine Error Graph, and an app.yaml file. The error on opening the website Logger in GCP showing no error The error graph on the GAE App.yaml file I have no idea why it suddenly started throwing this error. -
Django Model how to order by vote time?
So I have three models, User, Post, and UserVote: User is default django.contrib.auth user Post definition: class Post(models.Model): num_likes = models.IntegerField(default=0) num_dislikes = models.IntegerField(default=0) # when deleting users, we should simply set user.is_active to False, # that way this doesn't break user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=200, default="") UserVote: class Action(models.TextChoices): UP = 'u' DOWN = 'd' class UserVotes(models.Model): voter = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ForeignKey(Post, on_delete=models.CASCADE) type = models.CharField(max_length=2, choices=Action.choices, default=Action.UP) time = models.DateTimeField('time voted on', default=timezone.now) class Meta: unique_together = ('voter', 'item') On a user's profile page, I want to return the posts a user upvoted in descending order of when their vote was cast. I'm kind of lost here. I can return the posts a user voted on that aren't theirs as such: def get_users_liked_defs(user_id): Post.objects.filter(uservotes__voter__id=user_id, uservotes__type=Action.UP).exclude(user_id=user_id) But I'm not sure what to pass to order_by ? It would be something like -uservotes__time but how would I specify that I want to order by a particular user_ids uservotes? I could also retrieve all the uservotes corresponding to a user and order those, but then how would I turn all those into Posts? -
how resolve selenium server error on the chrome browser window?
I am testing django site using selenium but I am getting server error(500) on the chrome window. this is what selenium reports back devTools listening on ws://127.0.0.1:63521/devtools/browser/81f40775-3efc-4c51-a00b-3458fe4cd903 E ====================================================================== ERROR: test_post_list_page (public-site-tests.functional_tests.blog.test_blog_list.BlogPostTests) Lets create some blog posts ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\gouth\PycharmProjects\work\teenstartup\pavan-staging\public-site-tests\functional_tests\blog\test_blog_list.py", line 43, in setUp email_field = self.browser.find_element_by_id('id_username') File "C:\Users\gouth\.virtualenvs\public-site-tests-ue9jU_Te\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 360, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "C:\Users\gouth\.virtualenvs\public-site-tests-ue9jU_Te\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element return self.execute(Command.FIND_ELEMENT, { File "C:\Users\gouth\.virtualenvs\public-site-tests-ue9jU_Te\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Users\gouth\.virtualenvs\public-site-tests-ue9jU_Te\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="id_username"]"} (Session info: chrome=84.0.4147.89) the code that is resposible for this here class BlogPostTests(StaticLiveServerTestCase): """All tests related to Post model will be tested here""" def setUp(self): """Lets set up the browser""" self.browser = webdriver.Chrome() # lets set up some live urls login_url = self.live_server_url+reverse('accounts:login') self.browser.get(login_url) self.browser.implicitly_wait(10) email_field = self.browser.find_element_by_id('id_username') -
Django: Use same inmemoryuploadedfile to POST to multiple remote API's
I am trying to use the same inmemoryuploadedfile to multiple remote APIs. The upload form consists of a single FileField. Once the user submits the file, I'm trying to use the same inmemoryuploadedfile to post the file to multiple remote APIs. The first remote API call with the file gets successfully received at the remote API end. However, the second remote API call seems to fail as the remote API cannot read the file properly. To debug, I set the two remote APIs with same exact code but deployed on different VMs. Still getting the same error. It seems like only the first API call receives the file correctly and the second call always fails. def form_valid(self, form): exp = form.save(commit=False) result1 = api_endpoint1(exp.image) # Passes result2 = api_endpoint2(exp.image) # Fails- Doesnt receive file correctly if result1.json() == result2.json(): print('All is Good!') If I swap result1 and result2 line, then result2 passes and result1 fails. Even if I do call same API, the second one fails: result1 = api_endpoint1(exp.image) # Passes result2 = api_endpoint1(exp.image) # Fails- Doesnt receive file correctly I tried reseeking the file with exp.image.seek(0), but it doesn't work. I could save the file and then send the … -
How to specify lookup_field in django
I'm going to use UpdateAPIView in django. When I completed the view and ran the server, the following error occurred. Expected view updateViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. I wonder why I shouldn't designate lookup_field as pk in my code and what I can use instead of pk. Here is my code serializers.py from rest_framework import serializers from .models import arduino class arduinoSerializers (serializers.ModelSerializer) : name = serializers.CharField(source='name.username', read_only=True) class Meta : model = arduino fields = ['name', 'temp', 'humi'] views.py from .models import arduino from .serializers import arduinoSerializers from rest_framework.viewsets import ViewSet from rest_framework.response import Response from rest_framework.generics import CreateAPIView, UpdateAPIView class arduinoViewSet (ViewSet) : serializer_class = arduinoSerializers def data (self, request) : queryset = arduino.objects.filter(name=self.request.user) serializer = arduinoSerializers(queryset, many=True) return Response(serializer.data) class createViewSet (CreateAPIView) : serializer_class = arduinoSerializers def perform_create (self, serializer) : serializer.save(name=self.request.user) def get_queryset (self) : user = self.request.user return arduino.objects.filter(name=user) def dataReceive (self, request) : queryset = self.get_queryset() serializer = arduinoSerializers(queryset, many=True) if serializer.is_valid() : perform_create(serializer) return Response(serializer.data) class updateViewSet (UpdateAPIView) : serializer_class = arduinoSerializers lookup_field = 'pk' def perform_update (self, serializer) : serializer.update(name=self.request.user) def get_queryset (self) … -
how to update object which has OneToOne relationship in django?
I need to update the integer-field in every time I send the request with post method I tried that with the three ways but I couldn't make it. the problem is that when I send a request the request is sent successfully but the data doesn't save. I asked this question before but I didn't get the answer so I hope if anyone can help me I will be thanks match_statics/views.py from django.shortcuts import render, redirect from match.models import Main from .models import Statistics from .forms import StaticForm from django.db.models import F def player_statics(request, pk): form = StaticForm() statics = Statistics.objects.filter(main_id=pk) main_pk = Main.objects.get(pk=pk) if request.method == 'POST': if 'short_pos' in request.POST: form = StaticForm(request.POST, instance=Main.objects.get(pk=pk)) if form.is_valid(): # static = Statistics.objects.filter(main_id=pk).update(short_pass=form.cleaned_data['short_pass'] + 1) # static = Statistics.objects.filter(main_id=pk).update(short_pass=F('short_pass') + 1) form.short_pass = form.cleaned_data['short_pass'] form.short_pass += 1 form.save() context = {'form': form, 'statics': statics, 'main_pk': main_pk} return render(request, 'match_statics/player_statics.html', context) match_statics/player_statics.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Player Statics</title> </head> <body> <div class="match-statics"> <div class="container"> <form method="post" action="{% url 'match_statics:player_statics' main_pk.pk %}"> {% csrf_token %} <div class="buttons"> <h2>Pass Position</h2> {% for field in form %} {{ field.as_hidden }} {% endfor %} <div>{{ statics }}</div> <input type="submit" name="short_pos"> <input type="submit" name="long_pos"> … -
Form Validation - Signup & Login error handling in Django
I am having troubles handling errors in my signup form particularly with password1 & 2 validation, existing username & email handling. Here is my form: from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import UserProfile from .models import Follow class RegisterForm(UserCreationForm): class Meta(): model = User fields = ('username', 'email', 'password1', 'password2') widgets = { 'username': forms.TextInput(attrs={'class': 'form-control', 'name':'username' }), 'email': forms.EmailInput(attrs={'class': 'form-control' }), # 'password1': forms.PasswordInput(attrs={'class': 'form-control' }), # 'password2': forms.PasswordInput(attrs={'class': 'form-control' }), } def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['password1'].widget = forms.PasswordInput(attrs={'class': 'form-control', 'name':'password'}) self.fields['password2'].widget = forms.PasswordInput(attrs={'class': 'form-control'}) def clean_password(self, *args, **kwargs): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password1 != password2: raise forms.ValidationError("Passwords don't match") return self.cleaned_data class UserProfileForm(forms.ModelForm): class Meta(): model = UserProfile fields = ('location', 'favourite_activity') widgets = { 'favourite_team': forms.TextInput(attrs={'class': 'form-control' }), } Here is my views.py: def registerView(request): regForm = RegisterForm() proForm = UserProfileForm() if request.method == 'POST': regForm = RegisterForm(request.POST) proForm = UserProfileForm(request.POST) if regForm.is_valid() and proForm.is_valid(): user = regForm.save(commit=True) profile = proForm.save(commit=False) profile.user = user profile.save() username = request.POST.get('username') password = request.POST.get('password1') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return redirect ('timeline') else: return HttpResponse("There was a problem signing … -
reactivate virtualenv when returning to a project the next day
I am new to django i started a project in a virtualenv then shutdown the computer when I was done for the day. so How do I return to the same virtualenv the next day to continue with the project? -
i would like to add a row from one table to another table according to the given id in django
i tried django queryset update() but in documentation it says it can only access one database table. i would like to make the condition that the row will be added in table if the another table field verification is true. i am using postgresql for database. class All(models.Model): sn=models.CharField(max_length=100,null=False, blank=False) munID=models.CharField(max_length=100,null=False, blank=False, primary_key=True) fid=models.CharField(max_length=100,null=False, blank=False) ProvinceName=models.CharField(max_length=100,null=False, blank=False) DistrictName=models.CharField(max_length=100,null=False, blank=False) PalikaName=models.CharField(max_length=100,null=False, blank=False) PalikaType=models.CharField(max_length=100,null=False, blank=False) class All_Temp(models.Model): sn=models.CharField(max_length=100,null=False, blank=False) munIDD=models.CharField(max_length=100,null=False, blank=False, primary_key=True) fid=models.CharField(max_length=100,null=False, blank=False) ProvinceName=models.CharField(max_length=100,null=False, blank=False) DistrictName=models.CharField(max_length=100,null=False, blank=False) PalikaName=models.CharField(max_length=100,null=False, blank=False) PalikaType=models.CharField(max_length=100,null=False, blank=False) verification=models.CharField(max_length=100,null=False, blank=False) thank you in advance -
Django Graphene query filtering for foreign key
I have a django model class Person(models.Model): name = models.CharField() address = models.CharField() class Blog(models.Model): person = models.ForeignKey('Person', on_delete=models.CASCADE, blank=False, null=False) text = models.TextField() How do I write a graphene schema that allows query filtering by a foreign key? class Query(graphene.ObjectType): blog = graphene.Field(BlogType) blogs = graphene.List(BlogType, person=graphene.???, #Foreign Key call here text=graphene.String()) def resolve_blog(self, info, id): return Blog.objects.get(pk=id) def resolve_blogs(self, info, person = None, text = None, **kwargs) if person: filter = Q(person__icontains = person.name) #Filter for foreign key return Blog.objects.filter(filter) -
SMTPServerDisconnected error uploading multiple attachment with EmailMultiAlternatives
What I have I'm uploading multiple attachments with EmailMultiAlternatives from admin in Django. works great for one or several lightweight files, but when I try to upload multiple files, say 2 or 3 that are heavy, it keeps loading the page and after a moment it throws the error SMTPServerDisconnected. Custom wrapper function to send mail def send_mail( subject: str, message: str, recipient_list: List[str], from_email: Optional[str] = None, **kwargs: Any, ) -> int: """Wrapper around Django's EmailMultiAlternatives as done in send_mail(). Custom from_email handling, special Auto-Submitted header and optional attachment files. """ if not from_email: if hasattr(settings, "DEFAULT_FROM_EMAIL"): from_email = settings.DEFAULT_FROM_EMAIL else: from_email = "webmaster@localhost" connection = kwargs.get("connection", False) or get_connection( username=kwargs.get("auth_user", None), password=kwargs.get("auth_password", None), fail_silently=kwargs.get("fail_silently", None), ) multi_alt_kwargs = { "connection": connection, "headers": {"Auto-Submitted": "auto-generated"}, } mail = EmailMultiAlternatives( subject=subject, body=message, from_email=from_email, to=recipient_list, **multi_alt_kwargs, ) html_message = kwargs.get("html_message", None) if html_message: mail.attach_alternative(html_message, "text/html") attachments = kwargs.get("attachments", None) if attachments: for attachment in attachments: if isinstance(attachment, MIMEBase): mail.attach(attachment) # type: ignore else: mail.attach(*attachment) return mail.send() Custom admin class MessageFileInlineAdmin(admin.StackedInline): """Edit Message File on the same Message admin page. https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.TabularInline """ model = MessageFile extra = 1 @admin.register(Message) class MessageAdmin(admin.ModelAdmin): """Representation of a Message model in the admin interface.""" inlines = … -
How to integrate Django's oAuth backend with google assistant's webhook intents?
I followed the tutorial on auth0 https://auth0.com/docs/quickstart/webapp/django/ and was able to get a webpage that allows for user creation based on auth0 authentication. It uses social_core.backends.oauth with a middle layer that processes some of the authentication. I've also set up a test for my google home action device that sends an action.devices.SYNC via webhook and it gives me an authorization/bearer key that I should use to send to auth0 to retrieve userinfo that will allow me to access this bearer's account information, so that I can use the email address to access additional info in my server for smart home actions. I see that in the example, by the time it gets to: def dashboard(request): user = request.user auth0user = user.social_auth.get(provider='auth0') that request has a user object that lets me retrieve additional information on the user. How do I do the same thing with my webhook? It does not have a user object, but I'm not sure how to patch that into my existing webhook handler, it uses: class frontEndConsumer(AsyncHttpConsumer): async def http_request(self, request): # processes request object, extracts header and body, etc -
How do I remove a model item and adding a new item in Django?
I am getting this error. django.core.exceptions.FieldError: Unknown field(s) (description) specified for Todo I deleted my migrations folders. I tried migrating my files using the updated items. Originally I had this- class Todo(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=100) I tried to change it to this, but it won't let me. class Todo(models.Model): title = models.CharField(max_length=50) completed = models.BooleanField(default=False) What can I do besides starting over? Thank you. How do I remove a model item and adding a new item in Django?