Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change in migration behaviour between Django 1.7 & 1.8
I'm in the process of migrating an old Django app from Django 1.7. My current method is basically go to up a version then run manage.py test to see what I need to fix. Something appears to have changed in Django 1.8 that breaks some of the existing migrations. The following worked in Django 1.7 but breaks under 1.8 def load_pilotranks(apps, schema_editor): PilotRank = apps.get_model('warbook', 'PilotRank') ranks = [ { 'rank' : 'Champion', 'min_piloting' : 0, 'min_gunnery' : 0, 'skills_limit' : 0 } , { 'rank' : 'Star', 'promotion': 'Champion', 'min_piloting' : 0, 'min_gunnery' : 0, 'skills_limit' : 0 } , { 'rank' : 'Contender', 'min_gunnery' : 3, 'min_piloting': 4, 'skills_limit': 2, 'auto_train_cp': 1, 'promotion': 'Star' } , { 'rank' : 'Rookie', 'min_gunnery' : 4, 'min_piloting': 5, 'skills_limit': 1, 'auto_train_cp': 2, 'promotion': 'Contender' } ] for rank in ranks: if 'promotion' in rank: rank['promotion'] = PilotRank.objects.get(rank=rank['promotion']) PilotRank.objects.create(**rank) Now this yields the error: ValueError: Cannot assign "": "PilotRank.promotion" must be a "PilotRank" instance. (While this example could probably be fixed by replacing the offending code with a JSON fixture, there are more complicated examples that would be harder to address). The common denominator appears to be that the Model object returned … -
fix error while installing mysqlclient on python3.7 using cloudlinux python selector
this is my first time question on stackoverflow. a few days ago, i've been trying to setup a python app on my cpanel server. it was about a django project i've been working on. so i wanted to install mysqlclient using pip tool. but i was getting this output error: cPanel, cloudlinux os, apache latest version, python and ruby selector installed pip install mysqlclient: version node not found for symbol SSLeay@OPENSSL_1.0.1 /usr/bin/ld: failed to set dynamic section sizes: Bad value collect2: error: ld returned 1 exit status error: command 'gcc' failed with exit status 1 pip install mysqlclient output: Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Complete output from command /home/airtab/virtualenv/public__html_test/3.7/bin/python3.7 -u -c 'import setuptools, tokenize;__file__='"'"'/tmp/pip-install-4c1a9d8u/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-fm79t5sn --python-tag cp37: ERROR: /opt/alt/python37/lib64/python3.7/distutils/dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.7 creating build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.7/MySQLdb creating build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants … -
message send succesfully to whatsapp number but message_status coming (F) Failed
I am using this library https://github.com/mukulhase/WebWhatsapp-Wrapper In this I am able to send message on whatsapp number but in my response message_status coming 'F' please me this point! -
NoReverseMatch error for combined form and model_formset
I have been trying to create a for that combines parent and child models using model_formsets by following use case three in this tutorial. Models class Shoppinglist(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=2000) created = models.DateField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='lists', on_delete=models.CASCADE) last_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=80, unique=True) amount = models.IntegerField(default=1) shoppinglist = models.ForeignKey(Shoppinglist, on_delete=models.CASCADE) def __str__(self): return self.name URLs urlpatterns = [ url(r'^shoppinglists/(?P<pk>\d+)/$', views.shoppinglist_list, name='shoppinglist_list'), url(r'^shoppinglists/new/$', views.create_shoppinglist_with_items, name='shoppinglist_new'), ] Forms class ShoppingListForm(forms.ModelForm): description = forms.CharField( widget=forms.Textarea( attrs={'rows': 5, 'placeholder': 'Tell us about your list?'} ), max_length=4000, help_text='The max length of the text is 4000 characters.' ) class Meta: model = Shoppinglist fields = ['name', 'description'] ItemFormset = modelformset_factory( Item, fields=('name', 'amount'), extra=1, widgets={ 'name': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter Item Name here' } ) }, can_delete=True ) View @login_required def create_shoppinglist_with_items(request): template_name = 'list_with_items.html' if request.method == 'GET': listform = ShoppinglistForm(request.GET or None) formset = ItemFormset(queryset=Item.objects.none()) elif request.method == 'POST': listform = ShoppinglistForm(request.POST) formset = ItemFormset(request.POST) if listform.is_valid() and formset.is_valid(): shoppinglist = listform.save(commit=False) shoppinglist.created_by = request.user shoppinglist = listform.save() for form in formset: item = form.save(commit=False) item.shoppinglist = shoppinglist item.save() return redirect('shoppinglist_list', pk=shoppinglist.pk) return render(request, template_name, { 'listform': listform, 'formset': formset, }) … -
Does coupling API star and Django rest framework makes sense?
I’m just a new dev in python and Django area. And I’ve litteraly find out about apistar and how well it intagrates OpenAPI Specifications. I already I’m working on a project (microservices design) where I have a bunch of rest services (developped using django-rest-framework) For some reason I want to use apistar for docs, validating OAS schema and making requests to the servers referenced in those schemas. Does it makes sense to use apistar only for that use case ? -
Getting the same results as reading from local space by processing files directly through the buffer
This is a web application and it is developed by Python 3.7 with Django. It requires to retrieve audio files from a user from then the file will be processed by Base64UrlEncode method and send to a third-party api. The api only accepts processed result file read from io.BufferedReader. The current working method is to save the file to server's local space, open it, then read via io.BufferedReader and process the return value to get the result file. After the api successfully accepts the file, it will be deleted. Is there any ways that I do not have to open the file from server's local space, instead, directly processing it through the buffer? I tried to use InMemoryUploadedFile.read() then process it by Base64UrlEncode, but the api does not accept it. This is the working code, the api accepts the file sent to it: '''def getBody(filepath): binfile = open(filepath, 'rb') data = {'audio': base64.b64encode(binfile.read())} print(data) print('data:{}'.format(type(data['audio']))) print("type(data['audio']):{}".format(type(data['audio']))) return data aue = "raw" engineType = "sms16k" audioFilePath = r"C:\Users\HiWin10\Desktop\pytes\tessstdd.wav" r = requests.post(URL, headers=getHeader(aue, engineType), data=getBody(audioFilePath)) ''' I've tried to change '''binfile = open(filepath, 'rb') data = {'audio': base64.b64encode(binfile.read())} ''' to '''binfile = request.FILES.get('upfile') data = {'audio': base64.b64encode(binfile.read())} ''' The api does not … -
I cannot see Cathegory list admin, How to fix that
I registred Category admin in models.py. I added that model in Post model via ForenKey. But when i log into admin console i cannot see my Categories, I just see Category Object(1), Category Object(2) and so on. I will provide you a print screen and a code. http://prntscr.com/nxt25y instead if Japanese Kitchen or any other category (im working blog for chef), i see Category Object, the one that i highlighted on printscreen. I think its not a big deal but i didnt worked on django for quite some time so i forgot a lot. Can you spot a mistake? Thanks guys from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.utils.text import slugify from ckeditor_uploader.fields import RichTextUploadingField class Category(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(max_length=150) class Meta: ordering = ('name',) verbose_name = 'catergory' verbose_name_plural = 'catergories' def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField( help_text="A short label, generally used in URLs.", default='', max_length=100) category = models.ForeignKey( Category, on_delete=models.CASCADE, default='New category') image = models.ImageField(default='default.jpg', upload_to='profile_pics') content = RichTextUploadingField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['-date_posted'] def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def get_absolute_url(self): … -
How to display changelist of multiple models in django admin?
I need to display multiple models in django admin change list view. I want to use single search box to filter all of them at once. Is there an easy way to do it? My idea was to inherit from admin site, add another view to it and iterate over models in modified change_list.html but i can't import models and ModelAdmins because i get django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. error so i can't get the same context that django uses to render regular change_list.html. What's the correct way to do it? Is there simpler approach? -
Redirect to root url in AJAX
I'm looking for a way to start URL with ('') instead of ('search/') in AJAX request. I can workaround this problem simply add new path in URL dispatcher with path('search/email_add/<int:pk>/', views.email_add, name="email_add_from_search") but it's not a DRY method and a RedirectView not satisfy me. It works properly when I'm using add-phone.js script while in root URL. Error Not Found: /search/email_add/41/ while using script in ('search/') URL Ajax Request $.ajax({ url: 'phone_add/'+person_id+'/', method: 'POST', data: { 'phone': phone, }, error: function(result){}, success: function(result){}, urls.py urlpatterns = [ path('', views.contact_list, name="contact_list"), # GET path('add/', views.contact_add, name="contact_add"), # POST path('search/', views.contact_search, name="contact_search"), # GET path('delete/<int:pk>/', views.contact_detail, name="contact_delete"), # DELETE path('edit/<int:pk>/', views.contact_detail, name="contact_edit"), # POST path('phone_add/<int:pk>/', views.phone_add, name="phone_add"), # POST path('email_add/<int:pk>/', views.email_add, name="email_add"), # POST # path('search/phone_add/<int:pk>/', views.phone_add, name="phone_add_from_search"), # path('search/email_add/<int:pk>/', views.email_add, name="email_add_from_search"), ] -
Django-Haystack less than or equal to is not working properly
I am using django-haytsack in my django-application. I have to filter Searchqueryset based on salary which is a integer field. Trying to filter using lte but its not giving proper result. What I'm already tried: search_indexes.py: class UserSkillsProfileIndex(indexes.SearchIndex, indexes.Indexable): ... salary = indexes.IntegerField(model_attr='salary',null=True) Query: search_models = [UserSkillsProfile] qs = SearchQuerySet().order_by('last_updated_time').filter(salary__lte=int(min_sal)).models( *search_models) When I give min_sal value as 5000 it returns results which salary greater than the min_sal also including the lesser value. I need to get the results lesser than 5000. -
abstract model in django - no table in db for derived class
I have create two class in model.py class ForeginStrField(models.Model): class Meta: abstract = True name = models.CharField(max_length=300) def __str__(self): return self.name class Owner(ForeginStrField): pass After deleting db and all migrations (I want to clean project) and execute makemigaration and migrate in db there is no class table for Owner: "Exception Value: no such table: server_owner" How should I make derivation in order table for Owner will be created? Django version 2.2.1 -
Pushing Folder/Files to github for the existing repo using gitpython
I am pushing a folder to the existing repo in Github using Gitpython. But the problem is, it is asking for username and password every time I try to call the method. I want to include the credentials inside the code so that it can read itself while pushing the folder. I tried to pass the credentials in the following way but getting some error which I am not able to figure it out. I have tried these links but nothing has worked yet. https://developer.github.com/v3/, https://buildmedia.readthedocs.org/media/pdf/pygithub/latest/pygithub.pdf, How do I push new files to GitHub?. from git import Repo from github import Github from pdb import set_trace as bp repo_dir = '--------' repo = Repo(repo_dir) # using username and password g = Github("-----", "------") folder_path = '----------' commit_message = 'Add New file' repo.index.add(folder_path) repo.index.commit(commit_message) origin = repo.remote('origin') origin.push() So, I am getting this error "AttributeError: 'Repository' object has no attribute 'index'". -
How to create and submit multiple instances of a form on a single page?
I want 3 instance of a URL input form so I can submit up to 3 different URLs. forms.py class AdditemForm(forms.Form): url = forms.URLField( label='Add Item', widget=forms.URLInput( attrs={ "class": "form-control", })) view.py def ItemDetail(request, pk): listitem = comparelist.objects.get(id=pk) if request.method == 'POST': form = AdditemForm(request.POST) if form.is_valid(): url = form.cleaned_data.get("url") items.objects.create( link=url, name=product_name, price=price, store=store, ) return HttpResponseRedirect(request.path_info) else: form = AdditemForm() template = 'itemdetail.html' context = { "comparelist": listitem, "form": form, } return render(request, template, context) I'm using a form snippet I found in a tutorial: {% load widget_tweaks %} <form method="post" class="form"> {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} {% render_field field class="form-control is-valid" %} {% endif %} {% else %} {% render_field field class="form-control" %} {% endif %} {% if field.help_text %} … -
Pyhon Django what's the problem? / 'NoneType' object has no attribute 'page_range'
what's the problem? i can't find problem... what should i do? Error : AttributeError at / ('NoneType' object has no attribute 'page_range') Exception Location: get_context_data, line 15 from django.views.generic import ListView from django.core.paginator import Paginator from post.models import Post class Index(ListView): model = Post template_name = 'index.html' context_object_name = 'object' paginated_by = 5 def get_context_data(self, **kwargs): context = super(Index, self).get_context_data(**kwargs) paginator = context['paginator'] page_numbers_range = 5 max_index = len(paginator.page_range) // <--- error line page = self.request.GET.get('page') current_page = int(page) if page else 1 start_index = int((current_page - 1) / page_numbers_range) * page_numbers_range end_index = start_index + page_numbers_range if end_index >= max_index: end_index = max_index page_range = paginator.page_range[start_index:end_index] context['page_range'] = page_range return context -
Django and folium integration returns 'None'
I am trying to use folium to get maps in my django app. Here's the code: def map(request): data = pd.DataFrame({ 'lat': [77, 75, 72, 77, 78], 'lon': [28, 26, 19, 29, 30], 'name': ['Buenos Aires', 'jaipur', 'mumbai', 'gurgaon', 'dehradun'] }) m = folium.Map(location=[21, 78], tiles="Mapbox Bright", zoom_start=4.75) for i in range(0, len(data)): folium.Marker([data.iloc[i]['lon'], data.iloc[i]['lat']], popup=data.iloc[i]['name']).add_to(m) m.save('graph.html') context = {'map': m} print("context is", context) return render(request, 'classroom/teachers/map.html', context) Urls.py path('map', teachers.map, name='map'), HTML <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ map.render }} </body> I expect it to show a map with some markers on the given latitude and longitude, but something is wrong. What do I need to change to get the expected result ? -
How to redirect html page to another html page after posting the data through html page in django
After posting the data through html page that data will be stored in database and redirect the another html page. but in my case data stored in database and redirecting same page. but I want render another page. Here models.py code class Post(models.Model): title= models.CharField(max_length=100, unique=True) content= models.TextField() view.py file def createpost(request): if request.method == 'POST': if request.POST.get('title') and request.POST.get('content'): post = Post() post.title = request.POST.get('title') post.content = request.POST.get('content') post.save() return render(request, 'emp.html') emp.html file <html lang="en"> <head> <title>Create a Post </title> </head> <body> <h1>Create a Post </h1> <form action=" " method="POST"> {% csrf_token %} Title: <input type="text" name="title"/><br/> Content: <br/> <textarea cols="35" rows="8" name="content"> </textarea><br/> <input type="submit" value="Post"/> </form> </body> </html> Here is the html file I want to give the html page after posting the data through html page inserted.html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Successfully inserted!!!</h1> </body> </html> -
Can I define the options of the selectbox directly in django createview?
Can I define the options of the selectbox directly in createview? When selecting for a category field that refers to a category model Can these rules be applied? For example The author of the category content displayed as an option should be me. -
how to render PNG images without background in django templates?
I need to display the png transparent image in the frontend but am unable to format it correctly. i have tried to change the format to png but it is rendering a black background to it. class HelpCategories(models.Model): Name1 = ( ('Getting Started','Getting Started'), ('Pricing','Pricing'), ('Integration','Integration'), ('Security','Security'), ('Product Professionals','Product Professionals'), ('About Products','About Products'), ) Title = models.CharField(max_length=40, default='Getting Started') image = ImageField(upload_to='help_image', null=True, blank=True) def __str__(self): return self.Title def save(self, *args, **kwargs): if self.image: imageTemporary = Image.open(self.image).convert('RGB') outputIoStream = BytesIO() imageTemporaryResized = imageTemporary.resize( (400,400) ) imageTemporaryResized.save(outputIoStream , format='PNG', quality=300) outputIoStream.seek(0) self.image = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.png" %self.image.name.split('.')[0], 'image/png', sys.getsizeof(outputIoStream), None) super(HelpCategories, self).save(*args, **kwargs) i need to be able to see only the image object in the template. -
How to make an API call to another one of my views?
I am working on a simple investment-tracker app, which should get stock prices from an api and display them nicely for the user. I am having trouble, however to pass the necessary data through to the API call. views.py class PortfolioData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, tickers ,format=None): # how do I pass the tickers? stock_data = get_multiple_stock_details(tickers) # returns JSON response return Response(stock_data) @login_required def portfolio(request): user = request.user user_portfolio = Portfolio.objects.filter(user=user).first() return render(request, 'app/portfolio.html', {'portfolio':user_portfolio}) urls.py urlpatterns = [ path('', views.home, name="homepage"), path('api/portfolio/data/', views.PortfolioData.as_view(), name="portfolio-data"), path('portfolio/', views.portfolio, name='portfolio'), ] On the frontend I would make an ajax call to my PortfolioData view, in order to be able to process the data on the frontend. My biggest issue is how to pass the needed parameters. I tried to get the ticker symbols from the frontend using jQuery and then pass that to the endpoint url but I am not sure if this is the best way to go about this. -
Use Active Directory as Backend for Django Website
I need to sync my django application with the active directory so that the users login to the website using active directory credentials and the authentication backend for my website is the active directory. found a solution online ( https://pypi.org/project/django-adldap-sync/ ) but failed at the first step when trying to install "pip install django-adldap-sync". ERROR: Failed building wheel for python-ldap ERROR: running install fatal error C1083: Cannot open include file: 'lber.h': No such file or directory error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.21.27702\bin\HostX86\x64\cl.exe' failed with exit status 2 -
Use seperate existing database of users for django login
Is it possible to use an existing database of users without integrating it to the database of your django project. If yes, would i be able to use the user.is_authenticated and other django auths? Thanks! -
Error in migrating Kiwi with postgrsql in centos
When i load Kiwi database schema in centos6 with python3.6 in postgresql a programming error comes up with following django.db.utils.ProgrammingError: syntax error at or near "WITH ORDINALITY" LINE 6: Operations to perform: Apply all migrations: admin, attachments, auth, contenttypes, core, django_comments, kiwi_auth, linkreference, management, sessions, sites, testcases, testplans, testruns Running migrations: Applying testruns.0004_squashed...Traceback (most recent call last): File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.SyntaxError: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File … -
Exchange Authorization URL for Token Google OAuth2.0
After I get the authorization URL, I cannot exchange it for a token. Each time I call (authorization_response=self.request), I get hit with a AttributeError: 'WSGIRequest' object has no attribute 'lower' How do I exchange the Auth URL for a token? Code below: urlpatterns = [ path('ytauth/<int:pk>/', YtAuthView.as_view(), name='yt_auth'), path('oauth2callback/', Oauth2CallbackView.as_view(), name='oauth2callback') ] class YtAuthView(UserPassesTestMixin, UpdateView): model = Profile form_class = YtAuthForm template_name = 'yt_auth_update.html' def form_valid(self, form): CLIENT_SECRETS_FILE = "collab-web-client.json" SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl'] API_SERVICE_NAME = 'youtube' API_VERSION = 'v3' flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( client_secrets_file=CLIENT_SECRETS_FILE, scopes=SCOPES) flow.redirect_uri = 'https://127.0.0.1:8000/profiles/oauth2callback/' auth_flow = youtube_base() auth_url = auth_flow.get_authenticated_service() return redirect(auth_url) class youtube_base: def get_authenticated_service(self): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( client_secrets_file=CLIENT_SECRETS_FILE, scopes=SCOPES) flow.redirect_uri = 'http://127.0.0.1:8000/profiles/oauth2callback/' authorization_url, state = flow.authorization_url(access_type='offline') return authorization_url This is what my Authorization URL looks like. https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=clientIdhere.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Fprofiles%2Foauth2callback%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.force-ssl&state=t14XG3dAK0zQX8DOBGB0nO3Mk7nYes&access_type=offline class Oauth2CallbackView(View): def get(self, request, *args, **kwargs): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES) flow.redirect_uri = 'https://127.0.0.1:8000/profiles/oauth2callback/' flow.fetch_token(authorization_response=self.request) return redirect('http://127.0.0.1:8000/profiles/') Traceback: [05/Jun/2019 03:55:52] "POST /profiles/ytauth/29/ HTTP/1.1" 302 0 Internal Server Error: /profiles/oauth2callback/ Traceback (most recent call last): File "/Users/michaelninh/.local/share/virtualenvs/Collab--WeU7_dP/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/michaelninh/.local/share/virtualenvs/Collab--WeU7_dP/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/michaelninh/.local/share/virtualenvs/Collab--WeU7_dP/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/michaelninh/.local/share/virtualenvs/Collab--WeU7_dP/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Users/michaelninh/.local/share/virtualenvs/Collab--WeU7_dP/lib/python3.6/site-packages/django/views/generic/base.py", line … -
Question on Best Practices for Adding Additional Requirements for User Registration w/ Auto Created Linked Profile
Looking for recommendations on how to implement this feature. Looking to add a conditional field for user registration, say an authorization character field where the person is required to enter the correct code to register. Then immediately upon successful registration a profile is created. Looking to accomplish Three Things: Avoid using CAPTCHAs and provide a personal code for people to register Have a profile created for each registered user that is linked to the User model so I can easily add and remove fields without affecting the User model. Have the user choose a unique display name upon registration so that it shows the users display name throughout the application instead of the username from the User model. Current thoughts were to do a combination of Option 2 and 4 from this website, https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html I am quite new to Django so I am not sure what the best practices are to accomplish the above tasks. Prefer to have something that is easy to maintain with updates etc. If you were starting a new project what route would you take to implement these features? -
Django Queryset filter objects between 2 models iterating my values?
I'm doing a tax calculator and I have to do queries of one model and value them in another. I explain what I want to do. I have the following Models: class Tarifa_Sem(models.Model): limite_inferior_isr = models.DecimalField(max_digits=10, decimal_places=2) limite_superior = models.DecimalField(max_digits=10, decimal_places=2) class Calculadora_isr(models.Model): tarifa = models.ForeignKey(Tarifa_Sem, on_delete=models.CASCADE, null=True, blank=True, related_name='calculators') base_gravada = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) limite_inf_calculo = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) Now the problem in question is that I need to do the following. My model Tarifa_Sem has the following data: +--------------------------------------+ | Model Tarifa_Sem | +--------------------------------------+ |id |limite_inf | limite_superior | +---+-----------+----------------------+ | 1 | 0.01 | 133.21 | +---+-----------+----------------------+ | 2 | 133.22 | 407.33 | +---+-----------+----------------------+ | 3 | 133.22 | 610.96 | +---+-----------+----------------------+ | 4 | 133.22 | 799.68 | +---+-----------+----------------------+ | 5 | 133.22 | 814.66 | +---+-----------+----------------------+ | 6 | 133.22 | 1023.75 | +---+-----------+----------------------+ | 7 | 133.22 | 1086.19 | +---+-----------+----------------------+ | 8 | 133.22 | 1130.64 | +---+-----------+----------------------+ | 9 | 1130.65 | 1228.57 | +---+-----------+----------------------+ | 10| 1130.65 | 1433.32 | +---+-----------+----------------------+ | 11| 1130.65 | 1638.07 | +---+-----------+----------------------+ | 12| 1130.65 | 1699.88 | +---+-----------+----------------------+ In my Calculator model I have the following data inside base_gravda: +--------------------------------------+ | …