Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
social django package for facebook signin shows url error
When am using social django package for facebook signin but it shows error as : Can't load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings. In the fb app urlredirect provided is https://localhost:8000 . -
Django: Get User first_name
I can't figure out how to return the string representation of the User object's first_name and last_name fields. The User is built into Django's from django.contrib.auth import get_user_model. I want a table UserDetails containing extra info on the user so I want the Django admin to display the name of the user the details belong to. def __str__(self): return str(self.User.first_name) + ' ' + str(self.User.last_name) This is what I did but it is being presented as: I've tried changing model representations in Django admin before. User seems to behave differently though. -
How to allow only source code files (any language) in Django
In my webapp user can upload any source code (.py, .java etc..) of any programming language. I am trying to implement to restrict all files other than source code files of any language like pdfs , videos etc. I can't have a list of language extensions like .py, .js because user can upload any language source code. I can't even have list of filetypes to restrict like .pdf, .doc etc... Is there a django app which will handle with only language specific files for my problem. -
Django rest framework: De serializing a string to an integer and vice versa
We are using Django Rest framework to serialise and deserialise json response from a third party API. I need to translate the string field values to a numeric value in our system. The JSON response is given below { "result": "win" # Other values include "loss"/"inconclusive"/"pending" } Django Model class Experiment(Model): RESULTS = ( (1, 'win'), (2, 'loss'), (3, 'inconclusive'), ) inferred_result = models.IntegerField(choices=RESULTS, null=True, blank=True) Django Serializer Class class ResultsSeializer(serializers.ModelSerializer): # Need to convert "result" from "string" to "int" and vice versa. class Meta: model = models.Experiment I want to convert the inferred_result integer value to string equivalent and vice versa. I don't know how to do that. I could use this approach: Django rest framework. Deserialize json fields to different fields on the model if this is a good idea to convert integers to string. How do I convert string to int? I am new to django rest api and django. -
How configure a django project in apache2 step by step? (Ubuntu)
I need to configure my project in django in apache2 using ubuntu. These are the files that I have configured and how I have done it. My django project is /var/www/auxiliar_api directory. /etc/apache2/sites-available/auxiliar_api.conf <VirtualHost *:80> WSGIDaemonProcess auxiliar_api.com python-home=/usr/bin/python3.5 python-path=/$ WSGIScriptAlias / /var/wwww/auxiliar_api/auxiliar_api/wsgi.py ServerAdmin example@gmail.com ServerName auxiliar_api.com ServerAlias www.auxiliar_api.com DocumentRoot /var/www/auxiliar_api/auxiliar_api Alias /static/ /var/www/auxiliar_api/static/ <Directory /var/www/auxiliar_api/static> Require all granted </Directory> <Directory /var/www/auxiliar_api/auxiliar_api> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> /var/www/auxiliar_api/auxiliar_api/wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "auxiliar_api.settings") application = get_wsgi_application() When I try to access localhost this is the error that I get in the browser Forbidden You don't have permission to access / on this server. Apache/2.4.18 (Ubuntu) Server at localhost Port 80 I need to know what other files I should configure and how? Also if I need to modify some of the configurations that I have made and what do I show them? Thanks for any answer. -
what is the best practice to solve this in Django
looks like this in browser: My Model: The html: <div class="container"> <h1 class="display-1">Name, Generator!</h1><hr> <div class="alert alert-light" role="alert"> Fill in the catagories by your desired choice —and push generate </div> <br> <form> <div class="row"> <div class="col-md-3"> <input type="search" class="form-control" placeholder="First Letter"> </div> <div class="col-md-3"> <input type="search" class="form-control" placeholder="Origin"> </div> <div class="col-md-3"> <input type="search" class="form-control" placeholder="Gender"> </div> <div class="col-md-3"> <input type="search" class="form-control" placeholder="Religion"> </div> </div><br> </form> <br> <p class="text-center"> <button type="button" class="btn btn-dark">Genarate</button> </p> <p class="text-center"> "Results must be shown here with pagination" </p> </div> Please show me the way how do I generate this query. It will help me a lot. -
How can I make recipient_list of send_mail variable?
I am building EC market place with Django. We have created shop list page and shop details page. Furthermore, I would like to be able to send mail to each shop on the shop's detail page. However, we do not know how to change send_mail's recipient_list to the mailAddress of each shop when sending mail on the shop details page. ■ view.py from django.views import generic from django.views.generic.edit import ShopView from django.views.generic.edit import FormMixin from .models import Shop from .forms import ContactForm class ShopView(FormMixin, generic.DetailView): model = Shop form_class = ContactForm def get_template_names(self): return 'shopSearch/shop_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context def get_success_url(self): return 'contact/finish/' def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.send_email() return super().form_valid(form) ■ model.py class Shop(models.Model): name = models.CharField(max_length=255) mailAddress = models.CharField(max_length=100, null=True, blank=True) ■ form.py from django import forms from django.core.mail import send_mail from django.conf import settings class ContactForm(forms.Form): title = forms.CharField() email = forms.EmailField() contents = forms.CharField(widget=forms.Textarea) def send_email(self): subject = self.cleaned_data['title'] from_email = self.cleaned_data['email'] contents = self.cleaned_data['contents'] message = '\n\ncontens:\n' + contents + '\n\nfrom to:\n' + from_email to = <<mailAddress for each shop>> send_mail(subject, message, settings.EMAIL_HOST_USER, to) -
Post fails and get 479 error
I decide to change the topic of my learning logs When I press the submit button,it fails to redirect and report 479 error [15/May/2018 12:46:32] "POST /edit_topic/5 HTTP/1.1" 200 479 The edit_topic.html {% extends "learning_logs/base.html" %} {% block content %} <p> <a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a> </p> <p>Edit The Entry:</p> <form action="{% url "learning_logs:edit_entry" entry.id %}" method="POST"> {% csrf_token %} {{ form.as_p }} <button name="button">save changes</button> </form> {% endblock content %} The forms.py from django import forms from .models import Topic, Entry class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['text'] labels = {'text':''} The views.py def edit_topic(request, topic_id): topic = Topic.objects.get(id=topic_id) if request != "POST": form = TopicForm(instance=topic) print(request) # test point else: form = TopicForm(instance=topic, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("learning_logs:topic", args=[topic_id])) context = {'topic':topic, 'form':form} print(form) # test form return render(request, "learning_logs/edit_topic.html", context) The 'urls.py` urlpatterns = [ #Home Page url(r'^$', views.index, name='index'), # Show all the topics url(r'^topics/$', views.topics, name='topics'), # Detail pate for a single topics url(r'^topic/(?P<topic_id>\d+)/$', views.topic, name='topic'), # Page for adding a new topic url(r'^new_topic/$', views.new_topic, name='new_topic'), # Page for editing the topic url(r'^edit_topic/(?P<topic_id>\d+)$', views.edit_topic, name='edit_topic'), # page for adding a new Entry url(r"^new_entry/(?P<topic_id>\d+)$", views.new_entry, name='new_entry'), # page for … -
url token authentication is failing to redirect user
I'm failing to authenticate my user upon the registration. I've found out the solution for one time link token authentication, was tampering with ModelBackend you can see the basic solution here, I'll paste up my implementation because I'm using CBV for the view. Custom ModelBackend: from django.contrib.auth.backends import ModelBackend import logging from business_accounts.models.my_user import MyUser logger = logging.getLogger(__name__) class UrlTokenBackend(ModelBackend): """ Custom login backend that will accept token allow click url login """ def authenticate(self, request, token=None): try: user = MyUser.objects.get(token=token) except MyUser.DoesNotExist: logger.warning('My user=%s does not exist', user) return None if not user.is_active: return None def get_user(self, user_id): try: return MyUser.objects.get(pk=user_id) except MyUser.DoesNotExist: logger.warning('User with this id=%s does not exists', user_id) return None The authentication middleware is registered here AUTHENTICATION_BACKENDS = ( 'business_accounts.backends.UrlTokenBackend', # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ) Custom view is: from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.views.generic import View class UrlGatewayLogin(View): def get(self, request): token = request.GET.get('token') user = authenticate(token=token) login(request, user) return redirect('dashboard') and the url is url(r'^auth/login/', UrlGatewayLogin.as_view(), name='auth-login') Now I'll construct a url for the login, like so, http:/localhost:8000/auth/login/?token=12323344 so the … -
python django import csv to models.py
I have a function that import csv file to model. For some strange reason it only write the first row. I can't seem to figure out why its not writing the rest of the row. Appreciate any assistance def writeto_db(request): with open('/var/www/vmachines/registry/files/members.csv', 'rb') as csvfile: readata=csv.reader(csvfile,delimiter=str(u','),quotechar=str(u'"')) for row in readata: if row[0]!='First_Name': data=contacts() data.First_Name=row[0] data.Middle_Name=row[1] data.Last_Name=row[2] data.Date_of_Birth=row[3] data.Gender=row[4] data.Island=row[5] data.Province=row[6] data.Date_of_Bap=row[7] data.Congregation=row[8] data.Status=row[9] data.Comments=row[10] data.save() return render(request,'writesucc.html',locals()) -
Django @property used in Sum()
I'm trying to aggregate a list of integers from a model. The field that the integers are derived from are an @property decorator field. The decorator works as expected and within the template.html, if passed directly, displays without a problem. If however, I try and pass the @property field through .aggregate() the context passed into the template throws an error that basically says Cannot resolve keyword 'sum_thing' into field. followed by a list of model fields that don't include any of the decorator fields. My question is - how do you aggregate (Sum) derived fields from the model? #models.py class Foo(models.Model): a = 10 # a & b are both b = 5 # models.IntegerField() items @property def sum_thing(self): return self.a - self.b #views.py class Bar(generic.ListView): def get_context_data(self, **kwargs): qs = Foo.object.all() totals = {} totals['sumthing'] = qs.aggregate(total=Sum('sum_thing') context = { 'totals': totals } return context ** I've greatly simplified the models.py and the views.py. -
refrence values betweeen models in Django
I have 2 models in Django(one to many). Customer and Address. I need to store these values into a 3rd part end point in one API call. Also from the response I need to store the returned ids as Pk and Fk's in my DB. When i call is_valid is when I would like to do the API calls since I can raise the error returned by third parts as part of validation exercise. Is there a way in which I can do the validation and Api call in just 1 is_valid method? Basically can I access address model object/values when I am in clean() for addresss so that I can create 1 payload and then send it to 3rd party? Thanks -
Does anyone know how to look for an index inside the Jsonb?
Does anyone know how to look for an index inside the Jsonb? Ass.objects.get(id=id, contact__has_key=0) An error is shown operator does not exist: jsonb ? integer LINE 1: ... (("ass" -> 'contact') ? 0 AND "s... -
form object has no attribute 'cleaned_data' django
from django import forms from GeoCrime.models import type_crime_chicago,community_area_chicago class Ajouter_crime_form(forms.Form): CHOICES_type = [('Selectionner','Selectionner')]+[(elem.type_crime_label, elem.type_crime_label) for elem in type_crime_chicago.objects.all()] CHOICES_community = [('Selectionner','Selectionner')]+[(elem.nom_community, elem.nom_community) for elem in community_area_chicago.objects.all()] choice_bolean = (('False', 'False'),('True', 'True'),) id= forms.IntegerField(required=False,widget=forms.TextInput(attrs={'id':'disabled-input', 'name':'disabled-input', 'class':'form-control','readonly':'true'})) CaseNumber=forms.CharField(required=False,widget=forms.TextInput(attrs={'id':'casenumber', 'name':'casenumber', 'class':'form-control'})) Datecrime=forms.DateField(required=False,widget=forms.DateInput(attrs={'type':'date','id':'datecrime', 'name':'datecrime', 'class':'form-control'})) Timecrime=forms.TimeField(required=False,widget=forms.TimeInput(attrs={'type':'time','id':'timecrime', 'name':'timecrime', 'class':'form-control'})) Typecrime=forms.ChoiceField(required=False,choices=CHOICES_type,widget=forms.Select(attrs={'placeholder':'selectionner','id':'typecrime', 'name':'typecrime', 'class':'form-control'})) Autre=forms.CharField(required=False,widget=forms.TextInput(attrs={'id':'typecrimeAutre', 'name':'typecrimeAutre', 'class':'form-control'})) Description=forms.CharField(required=False,widget=forms.TextInput(attrs={'id':'Description', 'name':'Description', 'class':'form-control'})) IURC=forms.IntegerField(required=False,widget=forms.NumberInput(attrs={'id':'IURC', 'name':'IURC', 'class':'form-control'})) Domestic=forms.ChoiceField(required=False,choices=choice_bolean,widget=forms.Select(attrs={'id':'Domestic', 'name':'Domestic', 'class':'form-control'})) Arrest=forms.ChoiceField(required=False,choices=choice_bolean,widget=forms.Select(attrs={'id':'Arrest', 'name':'Arrest', 'class':'form-control'})) Community=forms.ChoiceField(required=False,choices=CHOICES_community,widget=forms.Select(attrs={'placeholder':'selectionner','id':'Community', 'name':'Community', 'class':'form-control'})) Locationdescription=forms.CharField(required=False,widget=forms.TextInput(attrs={'id':'Locationdescription', 'name':'Locationdescription', 'class':'form-control'})) x_coordinate=forms.FloatField(required=False,widget=forms.NumberInput(attrs={'id':'x_coordinate', 'name':'x_coordinate', 'class':'form-control'})) y_coordinate=forms.FloatField(required=False,widget=forms.NumberInput(attrs={'id':'y_coordinate', 'name':'y_coordinate', 'class':'form-control'})) Longitude=forms.FloatField(required=False,widget=forms.NumberInput(attrs={'id':'Longitude', 'name':'Longitude', 'class':'form-control'})) Latitude=forms.FloatField(required=False,widget=forms.NumberInput(attrs={'id':'Latitude', 'name':'Latitude', 'class':'form-control'})) Ward=forms.IntegerField(required=False,widget=forms.NumberInput(attrs={'id':'Ward', 'name':'Ward', 'class':'form-control'})) Block=forms.CharField(required=False,widget=forms.TextInput(attrs={'id':'Block', 'name':'Block', 'class':'form-control'})) Beat=forms.IntegerField(required=False,widget=forms.NumberInput(attrs={'id':'Beat', 'name':'Beat', 'class':'form-control'})) Disctric=forms.IntegerField(required=False,widget=forms.NumberInput(attrs={'id':'Disctric', 'name':'Disctric', 'class':'form-control'})) FBI=forms.IntegerField(required=False,widget=forms.NumberInput(attrs={'id':'FBI', 'name':'FBI', 'class':'form-control'})) Location=forms.CharField(required=False,widget=forms.TextInput(attrs={'id':'Location', 'name':'Location', 'class':'form-control'})) DateUpdate=forms.DateField(required=False,widget=forms.DateInput(attrs={'type':'date','id':'datecrime', 'name':'datecrime', 'class':'form-control'})) TimeUpdate=forms.TimeField(required=False,widget=forms.TimeInput(attrs={'type':'time','id':'timecrime', 'name':'timecrime', 'class':'form-control'})) if request.method == 'POST': if 'supprimer' in request.POST: list_crimes = request.POST.getlist('crimes') for element in list_crimes: crime_chicago.objects.filter(id_crime=element).delete() if 'ajouter_crime' in request.POST: p = "ifsubmit" crime_form = Ajouter_crime_form(request.POST) if crime_form.is_valid(): p="ajout" CaseNumber=form.cleaned_data['CaseNumber'] block=form.cleaned_data['Block'] iucr=form.cleaned_data['IURC'] primary_type=form.cleaned_data['Typecrime'] description_type=form.cleaned_data['Description'] location_description=form.cleaned_data['Locationdescription'] arrest=form.cleaned_data['arrest'] domestic=form.cleaned_data['Domestic'] beat=form.cleaned_data['Domestic'] disctric=form.cleaned_data['Disctric'] ward = form.cleaned_data['Ward'] community_get_id = community_area_chicago.objects.get(nom_community =form.cleaned_data['Community']) id_community=community_get_id.id_community fbi_code=form.cleaned_data['FBI'] x_coordinate=form.cleaned_data['x_coordinate'] y_coordinate = form.cleaned_data['y_coordinate'] year = datetime.now().year latitude = form.cleaned_data['Latitude'] longitude = form.cleaned_data['Longitude'] location = '('.join(latitude).join(',').join(longitude).join(')') date_crime=datetime.strptime(form.cleaned_data['Datecrime'],format_date_str).date() time_crime = datetime.strptime(form.cleaned_data['Timecrime'],format_time_str).time() update_date=datetime.strptime(str(datetime.now().date()),format_date_str).date() update_time = datetime.strptime(str(datetime.now().time()),format_time_str).time() get_type_crime_chicago=type_crime_chicago.objects.get(type_crime_label =primary_type) id_type_crime_chicago=get_type_crime_chicago.id_type_crime_chicago crime= crime_chicago.objects.create(id_crime=id,case_number=CaseNumber,block=block,iucr=iucr,primary_type=primary_type, description_type=description_type,location_description=location_description,arrest=arrest,domestic=domestic, beat=beat,disctric=disctric,ward=ward,id_community=id_community,fbi_code=fbi_code,x_coordinate=x_coordinate, y_coordinate=y_coordinate,year=year,latitude=latitude,longitude=longitude,location=location, date_crime=date_crime,time_crime=time_crime,update_date=update_date,update_time=update_time, id_type_crime_chicago=id_type_crime_chicago,type_crime_french=None) -
How to set href value in html using python
I have been trying to solve this problem: i want to set url to html a tag using loop. I tried this way. But it gives me error which is "Reverse for 'i.menuResolve' not found. 'i.menuResolve' is not a valid view function or pattern name". In case, "i.menuResolve" returns url which is '/sales/profile' etc. {% for i in userMenus %} <li> <a href="{% url 'i.menuResolve' %}" ></a> </li> {% endfor %} Please help if anybody knows this error? -
Django rest framework overriding creation rises error
I am trying to set the field of a model to the authenticated user by overriding the perform_create() method of a viewset, but I get an error. This is my model: class Reservation(models.Model): booking = models.CharField(max_length=15, primary_key=True) creator = models.ForeignKey(User, on_delete=models.PROTECT, related_name='user_reservations') agency = models.ForeignKey('GeneralApp.Agency', on_delete=models.PROTECT, related_name='agency_reservations') comment = models.TextField(null=True, blank=True) status = models.ForeignKey(ReservationStatus, on_delete=models.PROTECT, related_name='status_reservations') arrival_date = models.DateField() departure_date = models.DateField() register_date = models.DateField(auto_now_add=True) confirmation = models.CharField(max_length=15, null=True, blank=True) is_invoiced = models.BooleanField(default=False) def __str__(self): return "[{}]{}".format(self.booking, self.agency) def clean(self, *args, **kwargs): if self.arrival_date >= self.departure_date: raise ValidationError('Departure date must be later than Arrival date.') elif self.arrival_date <= timezone.datetime.now().date(): raise ValidationError('Arraival date must be later than today.') def save(self, *args, **kwargs): self.full_clean() super(Reservation, self).save(*args, **kwargs) This is my serializer: class ReservationSerializer(serializers.HyperlinkedModelSerializer): creator = serializers.ReadOnlyField(source='creator.username') class Meta: model = models.Reservation fields = ('booking', 'creator', 'agency', 'comment', 'status', 'arrival_date', 'departure_date') This is my view set: class ReservationViewSet(viewsets.ModelViewSet): queryset = models.Reservation.objects.all() serializer_class = serializers.ReservationSerializer def perform_create(self, serializer): serializer.save(owner=self.request.user) This is the error I get: TypeError at /reservations_manager/reservations/ Got a `TypeError` when calling `Reservation.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Reservation.objects.create()`. You may need to make the field read-only, or … -
Print() is never displayed inside python try/Except
I'm working on a Django app. Somewhere in my code, I use a try/except like this: try: myObject, created = MyObject.objects.update_or_create(title="Test") print("HAHAHA", myObject) except: pass It works well, myObject is saved, but print("HAHAHA", myObject) is never rendered. I don't know why. Please help -
django migrate "No migrations to apply."
I kind of know why when I do migrate it gives me the message of no migrations to apply but I just don't know how to fix it This is what happens. I added a new field named update into my model fields. I did a migration which created a file called 0003_xxxxx.py then I did a migrate now this worked fine. But then because of some reason, I have to remove the update field from the same model. So I removed it (more likey commented instead of really delete the code) then I did migration and migrate which removed the field in db. (created 0004_xxxxx.py) But sigh....some reason I have to add the field back again (this is why I only commented out) but then before I do the migration I removed the 0003_xxxx.py and 0004_xxxx.py files I wanted to remove those two files because this is actually the same or almost the same config as 0003_xxxx.py so I feel it's pointless having the 0003_xxxx.py and 0004_xxxx.py here...also when I go production, that's just another extra step for python to run. After I removed those two files, I did the migration which creates another 0003_xxxx.py but when I do … -
"GET /new_entry/5 HTTP/1.1" 200 466
When I am learning Django, The console usually hint me: "GET /new_entry/5 HTTP/1.1" 200 466 What's the purpose of 200 466? -
Django SyntaxError: invalid syntax 'else' statement?
for god sake I can't understand why I'm getting this error, it looks to be simple stuff but I've made a lot of modifications now and don't know what exactly caused this: (from Traceback): File "C:\Users\Lucas Cyrne Ferreira\Desktop\django- tutorial\mysite\contas\urls.py", line 2, in <module> from . import views File "C:\Users\Lucas Cyrne Ferreira\Desktop\django-tutorial\mysite\contas\views.py", line 38 else: ^ SyntaxError: invalid syntax from django.shortcuts import render, redirect, HttpResponse from contas.forms import ( RegistrationForm, EditPerfilForm, ) from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm from django.contrib.auth import update_session_auth_hash from django.contrib.auth.decorators import login_required def home(request): return render(request, 'contas/home.html') def register(request): if request.method=='POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect(reverse('home:home')) else: form = RegistrationForm() args = {'form':form} return render(request, 'contas/reg_form.html', args) def view_perfil(request): args = {'user': request.user} return render(request, 'contas/perfil.html', args) def edit_perfil(request): if request.method=='POST': form = EditPerfilForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect(reverse('home:perfil') else: form = EditPerfilForm(instance=request.user) args = {'form':form} return render(request, 'contas/edit_perfil.html', args) def trocar_password(request): if request.method=='POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect(reverse('home:perfil') else: return redirect(reverse('home:trocar_password')) else: form = PasswordChangeForm(user=request.user) args = {'form': form} return render(request, 'contas/trocar_password.html', args) My contas\urls.py: from django.urls import path from . import views from django.contrib.auth.views import ( login, logout, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView, … -
Dynamically Creating Users Django from Swift
I'm working on a Delivery app that connects to a local Django server but, I'm having issues creating users dynamically. Right now, I'm connecting my app via a hard code params I have this hard coded into my Swift App: let BASE_URL: String = "http://localhost:8000" let CLIENT_ID: String = "clkjlkjaklsdfjalksjdflkajslkdfjalksdfasdfasdf" let CLIENT_SECRET: String = "alajkldfjslfajeilrksldjflkasklzjklljlkdjsfkljKLJLKjsjioasdlkfjlfjasoidfa" Then an api manager that helps users log in: // API to login an user func login(userType: String, completionHandler: @escaping (NSError?) -> Void) { let path = "api/social/convert-token/" let url = baseURL!.appendingPathComponent(path) let params: [String: Any] = [ "grant_type": "convert_token", "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "backend": "facebook", "token": FBSDKAccessToken.current().tokenString, "user_type": userType ] Alamofire.request(url!, method: .post, parameters: params, encoding: URLEncoding(), headers: nil).responseJSON { (response) in switch response.result { case .success(let value): let jsonData = JSON(value) self.accessToken = jsonData["access_token"].string! self.refreshToken = jsonData["refresh_token"].string! self.expired = Date().addingTimeInterval(TimeInterval(jsonData["expires_in"].int!)) completionHandler(nil) break case .failure(let error): completionHandler(error as NSError?) break } } } But, I'm only connecting via that one Client ID and one user account. I need to dynamically create users in Django. How would I do that? -
DJANGO using SQLSERVER how do I trigger the procedures?
I'm using SQLSERVER as a database in a DJANGO project in college and I need to trigger my triggers and procedures through DJANGO, I've been looking for a few days to do this and I can not, can anyone help me? -
How to limit urls to admin users in Django
I'm currently limiting some urls to only logged-in users in Django by doing the following. urls.py urlpatterns = [ url(r'^$', login_required(views.MainView.as_view()), name='index') ] Is there a way to limit urls to only admin and staff users except for regular users? -
Django, account registration system error. Encountering a system error, we have notified site administrator, please try again later
I am working on a problem on a live django site. The problem is when a new user tries to register an account on the live site, the username and other information are successfully registered to database, except its password. what the user enters in the password field was not correctly saved in the database. Then, the front end throws a message System Error. Encountering a system error, we have notified site administrator, please try again later. But when I tested it locally, it worked just find. Since the site was deployed using Heroku, I checked the Heroku logs. Everything was fine since the logs were status 200. did anyone encounter similar problem and willing to share their experience? thank you. -
Two Django projects, one Postgresql database, and Docker
I have a django project with two apps. One is a basic homepage all static with an app specific django admin to control various aspects of the site. The other is a eCommerce django app. This is in one docker container. I have this connected to another docker container running the postgres image. Now, I have decided to split these two apps into two separate django projects and docker containers. Would it be reasonable to use just the one postgres container for both django containers? Or do I need to make two django containers?