Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
saving to django model gives null error even though model field has default value
When saving to a django model via a dict which does have the key and value {...,'type': None,...} the model field is type = models.CharField(max_length=3, choices=Type.CHOICES, default=Type.EITHER) However when trying to save I get an error: django.db.utils.IntegrityError: null value in column "type" violates not-null constraint Does the ORM in django not try to use the default value if a None is specified directly? How best should this be handled? -
how do i link my listview and detailsview in django templates such that when i click the list it then shows me the details
"im setting up my django-templates of a project o show schoolevents and job listings, i want its response to show me details of a list once i click the item on the list -can some one help am a newbie tp programming" i've tried adding slugfield to my models, changed the urls a couple of time but still i'm failing to reach my target models.py class Events(models.Model): title = models.CharField(max_length=80) host = models.CharField(max_length=80) venue = models.CharField(max_length=80) event_image = models.ImageField() details = models.TextField() posted_at = models.DateTimeField(auto_now_add=True) start_time = models.DateTimeField() end_time = models.DateTimeField() contacts = models.CharField(max_length=80) sponsors = models.CharField(max_length=80, null=True, blank=True) slug = models.SlugField(max_length=150, null=True, blank=True) class Meta: ordering = ('-posted_at',) form.py class EventsForm(forms.ModelForm): class Meta: model = Events fields = ( 'title', 'host', 'venue', 'details', 'start_time', 'end_time', 'contacts', 'sponsors', ) views.py class CreateEventsView(LoginRequiredMixin, CreateView): model = Events message = _("Your Event has been created.") form_class = EventsForm template_name = 'posts/create_events.html' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def get_success_url(self): messages.success(self.request, self.message) return reverse('list_events') class EventsListView(ListView): model = Events form_class = EventsForm context_object_name = 'all_events' template_name = 'events_list.html' success_url = reverse_lazy('list_events') def get_queryset(self): qs = super(EventsListView, self).get_queryset() return qs class DetailEventsView(DetailView): model = Events def render_to_response(self, context, **response_kwargs): if self.request.is_ajax(): return … -
"Cannot read property 'prefix' of undefined" javascript error in Django inlines.js
After updating Django to version 2.1.9 (from 1.9.8) I am receiving "Cannot read property 'prefix' of undefined" javascript error on Django admin page when there are inline models. The problem is in function tabularFormset in inlines.js file. This function takes two parameters: function(selector, options). options here should have prefix param but it appears that options are undefined. It looks like Django custom functions doesn't append selector as a first param, so options are first param. In result options param here is undefined. Does anyone know what the problem might be here? -
media not displayed in django deploy using nginx + gunicorn service
I am deploying a django app in a VPS (debian 9) using Nginx and gunicorn service. Everything works as expected but images uploaded by the user in media file are not displayed, 404 (not found). When I use Debug=True images are displayed, Static file works correctly in development and production. To run this app I have created a webuser without sudo rights and a group called webapps. Since it sems that nginx can't see the media I have changed the group to www-data, but still it doesn't work. There is a similar issue here but without accepted answer. Any help will be much appreciated. Bellow some important configurations: (web_env) webuser@:~/web_project$ ls -la total 72 drwxrwxr-x 10 webuser www-data 4096 Jun 11 20:30 . drwxr-xr-x 3 webuser webapps 4096 Jun 10 17:15 .. drwxr-xr-x 6 webuser webapps 4096 Jun 10 17:15 blog -rw-r--r-- 1 webuser webapps 655 Jun 10 17:15 environment.yaml drwxr-xr-x 2 webuser webapps 4096 Jun 10 17:15 .idea drwxr-xr-x 2 webuser webuser 4096 Jun 11 17:28 logs -rwxr-xr-x 1 webuser webapps 631 Jun 10 17:15 manage.py drwxrwxr-x 3 webuser www-data 4096 Jun 10 17:15 media -rw-r--r-- 1 webuser webapps 14417 Jun 10 17:15 posts.json -rw-r--r-- 1 webuser webapps 229 … -
How to Implement a Location Search / Maps in a Django Application
I would like to get some inputs on how should I go about proceeding to achieve the Following. I want to implement a Web App in Django which will look/search for 'My Supermarket Chain' within 'X KM' of my current location, and choose it and look for products available there. As an Example, let's make all the Dominos Chain as 'My Supermarket'. I have already implemented the Part in which the Products in each Stores are set. How would I go about achieving this? Let's say I have my Store Model as follow: class Store(models.Model): name = models.CharField() location = ?? Should I be adding the Logitude / Latitude of a Dominos Chain to the location field? or Should I use an API like Google Maps and change the things there? I am totally blank on how I should go about / learn to achieve this. Please suggest what all things I would need to learn and how to Apply those so that I can learn it and do it. -
UnboundLocalError: local variable 'r' referenced before assignment (Django)
I want to reference the value of an item company_id in a object company_obj created from a RESTful API call cwObj.get_company(company) and then pass that value to another API call cwObj.get_sites(company_id) and then return the object. However, I am getting an UnboundLocalError when I attempt to pass company_id to the API call. Through debug, I can see that company_id has the desired value so I am not sure why I am unable to then create another object using said value. Does this not mean the variable is indeed assigned? If not, what is the best practice to assign the variable before it reaches the cwObj.get_sites() call? Please let me know if any more information is needed, thanks! views.py def new_opportunity_location(request): company = request.GET.get('selected_company') company_obj = cwObj.get_company(company) company_id = company_obj[0]['id'] sites = cwObj.get_sites(company_id) context = {'sites': sites} return render(request, 'website/new_opportunity_location.html', context) -
Django - Make 3rd-party API call and django can no longer find base.html
I am trying to make a call to a third-party API in my Django app, more specifically in a views.py. Once I make this call, Django fails to find the template base.html. Essentially this is what's happening: user searches for a term in a search form the request gets sent to my view the view has an if statement to handle when the user is making a GET request, so this piece of logic handles the request the view makes a call to a separate function search_by_jobsite() written by me inside search_by_jobsite(), a call to a third-party API is made, and I pass the location of a .pkl file to the API. The location is /webapp/camera_search/api/pickle/config.pkl. Everything is fine and search_by_jobsite() retrieves the necessary information It returns the information back to the view, and the view goes on to define the context dictionary and attempts to render(request, 'siren_search.html', context). However, this is where it fails. The first line in siren_search.html is {% extends 'base.html' %}, so it starts looking for base.html but it's looking in the wrong directory. It is searching for base.html in /webapp/camera_search/api/pickle/ when base.html is located in /webapp/webapp/templates/base.html. For some reason when django goes to the pickle/ … -
django modelForm not validating added foreign key
I have a modelForm where I overwritte the init method to provide a predefined value from a FK. However when validating the form with the method is_valid() it fails as it says "Palabras" already exists but is not taking in consideration the FK "fk_funcion" as both are PK. Models.py class Palabras(models.Model): fk_funcion = models.ForeignKey(Funcion, related_name='funcion', on_delete=models.CASCADE) palabra = models.CharField(max_length=30, unique=True) porcentaje = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(100)]) class Meta: unique_together = ("fk_funcion", "palabra"), def __str__(self): return self.palabra Forms.py class PalabraForm(forms.ModelForm): class Meta: model = Palabras fields = ('palabra','porcentaje', "fk_funcion") def __init__(self, *args, **kwargs): fk_funcion = kwargs.pop('fk_funcion','') super(PalabraForm, self).__init__(*args, **kwargs) self.fields['fk_funcion']=forms.ModelChoiceField(queryset=Funcion.objects.filter(id=fk_funcion)) Views.py def create_palabra(request, pk_funcion): data = dict() if request.method == 'POST': form = PalabraForm(request.POST,fk_funcion=pk_funcion,,initial={'fk_funcion':pk_funcion}) #I have tried with and without the initial value if form.is_valid(): #Some action What do I have to modify in order to make the form to validate both "palabra" and "fk_funcion" in the modelForm. Thanks -
Store time stamps to database(Please read the description)
I am creating a Django web based application for freelancers ,that they would be paid for number of hours they have worked on a project and also a weekly report is to be generated for weekly work and for that i need to work with time stamps so how do i implement it ? I want to create a button of start timer and stop timer ,which records the time stamps of start timer and end timer? I have a User model which is extended to Freelancer and person who hires Freelancer ,How do i implement this? Where do i edit the model of time stamps? I have this model from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_freelancer = models.BooleanField('Freelancer status', default=False) is_hirer = models.BooleanField('Hirer status', default=False) class Freelancer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) hourly_rate = models.PositiveIntegerField(default=10) education = models.TextField(default='asia') professional_bio = models.TextField(blank=True, null=True) professional_title = models.TextField(blank=True, null=True) location = models.CharField(max_length=10, blank=True, null=True) Address = models.CharField(max_length=100, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) postal_code = models.PositiveIntegerField(blank=True, null=True) country = models.CharField(max_length=100, blank=True, null=True) class Hirer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) hourly_budget = models.PositiveIntegerField(blank=True, null=True) project_title = models.CharField(max_length=100, default='hi') project_description = models.TextField(blank=True, null=True) job_category = models.CharField(max_length=100) professional_bio = models.TextField(blank=True, null=True) professional_title … -
Custom FilterSet doesn't filter by two fields at the same time
I wrote custom FilterSet to filter queryset by two fields but it doesn't work properly when it's filtering on two fields at the same time. my FilterSet: class EventFilter(filters.FilterSet): values = None default = None category = filters.ModelMultipleChoiceFilter( queryset=EventCategory.objects.all(), ) interval = filters.CharFilter( method='filter_interval' ) class Meta: model = Event fields = ('category', 'interval') def filter_interval(self, queryset, name, value): if self.request.query_params.get('current_time'): try: interval = getattr(self, f'get_{value}_interval')() interval = list(map(lambda date: self.to_utc(date), interval)) return self.queryset.filter(Q(status=Event.STARTED) | (Q(status=Event.NOT_STARTED, start_at__range=interval))) except Exception as e: pass return queryset APIView: class ListEventsAPIView(generics.ListAPIView): serializer_class = ListEventsSerializer filter_class = EventFilter search_fields = 'title', filter_backends = filters.SearchFilter, DjangoFilterBackend def get_queryset(self): return Event.objects.filter(Q(status=Event.STARTED) | (Q(status=Event.NOT_STARTED) & Q(start_at__gte=date))) Here is generated SQL when I'm trying to filter only by category: SELECT "*" FROM "events" WHERE (("events"."status" = 'started' OR ("events"."status" = 'not_started' AND "events"."start_at" >= '2019-06-19T13:24:26.444183+00:00'::timestamptz)) AND "events"."category_id" = 'JNPIZF54n5q') When I'm filtering on both: SELECT "*" FROM "events" WHERE (("events"."status" = 'started' OR ("events"."status" = 'not_started' AND "events"."start_at" >= '2019-06-19T13:24:26.444183+00:00'::timestamptz)) AND ("events"."status" = 'started' OR ("events"."start_at" BETWEEN '2019-06-19T07:16:48.549000+00:00'::timestamptz AND '2019-06-30T20:59:59.000059+00:00'::timestamptz AND "events"."status" = 'not_started'))) -
Querying the data from data-lake gen 2 to python backend
I have python (Django) backend which needs to query the data from data-lake gen 2 based on the HTTP requests and provide the result as API to the end user interactively. How could I solve this use case? I am coming from database background and not so familiar with all the data analytics solutions provided by the cloud. The data is distributed in lots of structured TSV files. I decided to go with the data lake to utilize a few features such as partition and fast processing. I was planning to use U-SQL but since it only provides the result in the output file which is not so efficient in my case. Any better approach to solve this issue? Thanks in advance. -
How call specified item of model in html?
having a model named books, we can get name of second book by books.2.name, and name of 3rd book by books.3.name so, how can get books.i.name, where i is specified by user? -
How to use a single django codebase across multiple (and isolated) server installs and multiple databases
We would like to use the same django codebase to offer our service to multiple companies where each company would have their own install, own database completely isolated from the rest. Looking to find the best strategy to do this. We are at the planning stage. However we have identified the following requirements and potential problems/extra workloads. Requirements 1.) The codebase should be identical. 2.) Each install should have its own database which stores company specific records such as employee details, and also content to be delivered to the front end (copy and such like). Each company must have its own database. Potential problems 1.) Currently when we make database structural changes, we apply these using the django migration system. However, we currently have one install with hundreds of migrations, a new install would not need all of these, only the current version of the models. So we'd end up having to keep track of and produce and version control multiple different sets of migrations. How best to approach this. 2.) Some of the migrations we have in our project are data only, and they are simply not relevant to any new installations. It's also possible that going forward we … -
Django: How to not return all model fields
I'm using a Django system where each model has an associated serializer (pretty standard). In one model, the serializer is as follows: class ThingSerializer(ModelSerializerWithFields): class Meta: model = Thing fields = "__all__" and a model: class Thing(models.Model): class Meta: ordering = ("a", "b") thing_id = models.UUIDField(primary_key=True, default=uuid.uuid4, blank=True, editable=False) a = models.FloatField(null=True, blank=True, default=None) b = models.FloatField(null=True, blank=True, default=None) I want to implement a system that: if field a of Thing is not null, then field b is returned (on a GET request, for example), and if a is null then b is not returned. How (and where) can I do this? -
How to Filter by Post Arguments in ListView
I am trying to create a form in my ListView which POSTs to the ListView and filters by the POSTed attributes. This is in a Django 2.1 project. I have tried passing both self and request argunments to the post function but I am receiving the Exception below e.g. def post(self, request): results in a TypeError exception: post() takes 1 positional argument but 2 were given If I try to solve the error by removing one of the parameters so that only self is passed to the post() def post(self) function I receive the following TypeError exception: post() takes 1 positional argument but 2 were given Despite the fact that only self has been passed. I have tried only passing request and that results in the same thing. Lots of examples online show def post(self, request, *args, **kwargs) This results in the obvious exceptions of: too many values to unpack (expected 2) Removing all arguments results in a TypeError: post() takes 0 positional arguments but 2 were given class thing_dashboard(ListView): ''' All Orders processed ''' template_name = 'thing/orders_dashboard.html' paginate_by = 25 def post(self, request): queryset = Order.objects.all().order_by('-ordered_date') rejected = self.request.POST.get('rejected') if rejected == 'False': queryset = Order.objects.filter(state='rejected') return queryset return … -
Django Ajax: Not able to get data from my view method to template
I'm completely new to Ajax and Django. I'm trying to accomplish a task which to call an ajax method and update the textarea with the data returned from view. What exactly I'm trying to do? The user selects an option from the dropdown and submit, which internally calls an ajax method and Ajax has to call a particular method in my view. Once view should return a data and the same has to be shown on my webpage. The whole process should complete without page reload and dropdown value reset. Currently, I'm able to make ajax call successfully but not able to render the data on the template. Html and Ajax call: {% extends 'login/whitebase.html' %} {% load static %} <html> <head> <title>Log Hunt</title> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'resources/Newstyle.css' %}"> </head> <body> {% block body %} <div class="container-fluid"> <nav class="navbar navbar-inverse navbar-default" role="navigation"> <div class="container-fluid" style="background-color: #003554;position: absolute;top: 0px;right: -15px;width: 1290px;"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <img src="{% static 'images/envestnet-yodlee.svg' %}" style="width: 45%;padding: 8px"> </div> <button style="font-family:'Trebuchet MS';border-color:white;height: 34px;color: white;font-size: 14px;margin-right: 10px" name="YDocs" class="btn btn-outline-primary"> <i class="fas fa-book"></i> … -
mayan-edms's initiasetup command not wokring
I am installing mayan-edms 3.2.1, I followed the steps as explained in the documentation https://docs.mayan-edms.com/chapters/deploying.html. But i am stuck at initialsetup. When i run this command after applying all migrations its started installing package Bootstrap and then after sometime it shows error in installing that package. This are last few lines on running this command. Applying tags.0008_auto_20180917_0646... OK Applying user_management.0001_initial... OK Installing package: Bootstrap (=3.4.1)... Does anyone know what going wrong? Any help is appreciated. -
How to retrieve hierarchical selection data set into bootstrap modal?
I have a django website hierarchical selection data set stored in tables as follows, id parent_id category --------------------------------- 1 NULL Computers 2 NULL Phones 3 2 Nokia 4 3 Samsung 5 NULL Watch I just want to retrieve these data into bootstrap modal(to filter search result) like this site(hit the "Select Location" button). Could anyone tell me how do I achieve this? -
How can I solve an error when I migrate my Django models?
I want to migrate my model for create tables on my local PgSQL DB. It's not the first time that I'm doing that on this configuration but this time, that's fail. My manipulation : 1) I deleted my old database jlb_inventory 2) I recreated the database jlb_inventory empty 3) I deleted "0001_initial" on application's directory /migration 4) I ran command python manage.py makemigrations models.py # Table Etude class Study(models.Model): study_name = models.CharField(max_length=255, null=False) class Inventory(models.Model): watercourse = models.CharField(max_length=255, null=False) town = models.CharField(max_length=255, null=False) number_resorts = models.IntegerField(null=False) inventory_date = models.DateField(null=False) fk_study = models.ForeignKey(Study, on_delete=models.CASCADE) class Resort(models.Model): index_resort = models.IntegerField(null=False) name_resort = models.CharField(max_length=255) fk_inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE) class Taxon(models.Model): name_taxon = models.CharField(max_length=255, null=False) gi = models.IntegerField(default=0) class Sample(models.Model): MICRO_HABITAT_CHOICES = ( ('1', 'Habitat1'), ('2', 'Habitat2'), ('3', 'Habitat3'), ('4', 'Habitat4'), ('5', 'Habitat5'), ('6', 'Habitat6'), ('7', 'Habitat7'), ('8', 'Habitat8'), ) taxon_quantity = models.IntegerField(null=False) fk_taxon = models.ForeignKey(Taxon, on_delete=models.CASCADE) fk_resort = models.ForeignKey(Resort, on_delete=models.CASCADE) And my error django.db.utils.ProgrammingError: relation "business_data_entry_taxon" does not exist LINE 1: ...ame_taxon", "business_data_entry_taxon"."gi" FROM "business_... Someone knows what is the problem here ? Thanks! -
How to insert(Add) JSON data in MySql database through Postman or Rest API Framework using Django?
I have started coding in Python using Django and MySql recently.So, I am facing issue in simple inserting data(JSON format) in a table in MySql database.I have tried few things which I am mentioning below.But it did not work.And I am using the following - Python, Django Framework, MySql Database, mysqlclient connector, Rest API Framework, Postman. Please help me out with suggestions. from django.shortcuts import render, redirect from rest_framework.decorators import api_view from rest_framework.response import Response from .models import fetchdata from .serializers import fetchdataSerializers from rest_framework import status,response from rest_framework import viewsets from django.http import HttpResponse @api_view(['GET','POST']) def index(request): if request.method=='POST': try: _json = request.json _name = _json['name'] _email = _json['email'] _password = _json['pwd'] sql = "INSERT INTO tbl_user(user_name, user_email, user_password) VALUES(%s, %s, %s)" data = (_name, _email, _hashed_password,) conn = mysql.connect() cursor = conn.cursor() cursor.execute(sql, data) conn.commit() resp = jsonify('User added successfully!') serializer=fetchdataSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) -
Django Angular Integration index.html file
In my application we have to integrate django+ Angular. In this how can i render index.html as static. Everytime i have to keep {%static before script files.How can we automate this -
__init__() takes 1 positional argument but 2 were given Error on a very simple form function
I have this very simple form but I keep getting the error init() takes 1 positional argument but 2 were given Here is my code: models.py class Feedback(models.Model): name = models.CharField(max_length=100) contact = models.CharField(max_length=12) title = models.CharField(max_length=120) description = models.TextField(blank=True, null=True) summary = models.TextField(blank=False, null=False) created_on = models.DateTimeField(auto_now_add=True) forms.py class Feedback_form(BSModalForm): class Meta: model = Feedback fields = ['name', 'contact', 'title', 'description', 'summary'] views.py @login_required class Feedback_Create(BSModalCreateView): template_name = 'classroom/teachers/feedback.html' form_class = Feedback_form success_message = 'Success: Sign up succeeded. You can now Log in.' success_url = reverse_lazy('classroom:feedback_form') urls.py path('feedback/', teachers.Feedback_Create, name='feedback'), feedback.html {% load widget_tweaks %} <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h3 class="modal-title">Create Book</h3> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="{% if form.non_field_errors %}invalid{% endif %} mb-2"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% for field in form %} <div class="form-group"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {% render_field field class="form-control" placeholder=field.label %} <div class="{% if field.errors %} invalid{% endif %}"> {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> </div> {% endfor %} </div> <div class="modal-footer"> <button type="button" class="submit-btn btn btn-primary">Create</button> </div> </form> I do not understand what … -
Django keep getting 104 connection reset by peer caused by adding simple video, can't forward video
I want to add video to my django template. When I add it, video is unforwardable (I can't skip this video to other point, I can just play it from start to the end). Excatly the same issue happens when I open link to video in new browser tab. When I close/refresh this page console shows: [19/Jun/2019 11:22:23] "GET / HTTP/1.1" 200 9386 [19/Jun/2019 11:22:23] "GET /media/audio_and_video/videoplayback_lzlCjOR_Ftjx0GJ.mp4 HTTP/1.1" 200 9431145 [19/Jun/2019 11:22:24] "GET / HTTP/1.1" 200 9386 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 44798) Traceback (most recent call last): File "/usr/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer ---------------------------------------- Model: class Track(models.Model): title = models.CharField(max_length=40, null=True) description = models.CharField(max_length=500, null=True) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) miniature = models.ImageField(upload_to='images/track', default="defaults/default.png", validators=[validate_miniature_file_extension]) audio_or_video = models.FileField(upload_to='audio_and_video/', default="file_not_found", validators=[validate_track_file_extension]) favourite = models.BooleanField(default=False) def __str__(self): return self.title Template (".fields" because I use vuejs, but link to video works exactly as … -
Sending SMS to user entered data
I am using the Twilio API to send a SMS to a number fetched from the db ,entered by the user in the db. That number comes from the database meaning there are a lot of numbers to send to, but I am unable to understand on how to fetch the user entered number for the to field and for the body the user entered text. Note on Model: The logged in user creates a Person taking all their credentials(Number, email etc) through a form, then the logged in user creates an invite against any created Person (mentioned above). This Invite includes the Message (which I want to use as Twilio Body) Below is my code views.py def send_SMS(self,id): account_sid = os.environ["Twilio_account_sid"] auth_token = os.environ["Twilio_auth_token"] client = Client(account_sid, auth_token) client.messages.create( to= 'a number', from_="my Twilio number", body="Talha Here, Reply in Whatsapp, if you recieved this sms with a screen shoot") models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from datetime import date, datetime from django.dispatch import receiver from django.db.models.signals import post_save class PersonData(models.Model): user_relation = models.ForeignKey( User, on_delete=models.CASCADE) person_email = models.EmailField("Email", max_length=512) person_contact_number = models.PositiveIntegerField("Phone Number", blank=True, null=True) class Invite(models.Model): … -
How to fix django-allauth returning KeyError: ['key']?
I'm trying to add e-mail account verification in my django project, but i have some problems with it. What should i do to solve this trouble? There is my urls.py from django.conf import settings from django.urls import path, re_path, include from api import urls from rest_auth.registration.views import VerifyEmailView, RegisterView urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), re_path(r'^account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), re_path(r'^account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email') ] There is my settings.py (as for the subject) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'allauth', 'allauth.socialaccount', 'allauth.socialaccount.providers.vk', 'allauth.socialaccount.providers.google', 'allauth.account', 'rest_auth.registration', 'corsheaders', 'mainpage', 'combinator' ] EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_AUTHENTICATION_METHOD = 'username' ACCOUNT_EMAIL_VERIFICATION = 'mandatory' E-mail is sending correctly (as i suppose by console), But an attempt to go through verification leads to an error: [19/Jun/2019 16:04:08] "GET /account-confirm-email/MTU:1hdYJH:vsf9c1crzBoGBa70De731JG67eI/ HTTP/1.1" 500 97649 Internal Server Error: /account-confirm-email/MTU:1hdYJH:vsf9c1crzBoGBa70De731JG67eI/ Traceback (most recent call last): File "C:\Users\kotov_or\django_envs\IRM\envIRM\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\kotov_or\django_envs\IRM\envIRM\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\kotov_or\django_envs\IRM\envIRM\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\kotov_or\django_envs\IRM\envIRM\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\kotov_or\django_envs\IRM\envIRM\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\kotov_or\django_envs\IRM\envIRM\lib\site-packages\rest_framework\views.py", …