Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i store sensitive data in a Django project?
I'm building a project where i will be able to save an API key, then this key will be used to perform some operations on my site from an external python bot. Obviously, no one should access the key, except my code that will perform some tasks using those keys. At the actual moment, the keys are stored on my database and they are not encrypted, but now i would like to make this system as safe as possible, so that even if someone has access to my credentials, he can't use it. The problem is that i know very little about security and encription. My first thought was to encrypt the keys, but i don't really know how to do that. Basically, that's how it should work: the keys are submitted using a form -> the keys must be encrypted and saved on my db -> later on, when i need to perform a task, those keys should be decrypted in order to do what i need Is my approach correct? And how can i accomplish that in Django? Here is my current view: def homepage(request): if request.method == 'POST': # create a form instance and populate it with … -
Django: Accessing RIght-Hand Info From Left Joins
I'm doing a complex LEFT JOIN queries, but I'm not sure how to extract information from the joined tables. First, let's start with a few simplified sample models as an example: class Bar(models.Model): name = models.CharField(max_length=255) status = models.IntegerField(default=0) data = models.TextField(default=None) class Meta: db_table = 'bar' class FooBar(models.Model): bar = models.ForeignKey(Bar, on_delete=models.CASCADE, related_name='foobars') status = models.IntegerField(default=0) data = models.TextField(default=None) class Meta: db_table = 'foobar' class FuBar(models.Model): bar = models.ForeignKey(Bar, on_delete=models.CASCADE, related_name='fubars') status = models.IntegerField(default=0) data = models.TextField(default=None) class Meta: db_table = 'fubar' The "Bar" table has a one-to-many relationship to both the "FooBar" and "FuBar" tables. This also means that the "FooBar" and "FuBar" have an implicit many-to-many relationship. Here's the RAW equivalent of what I'm trying to do: SELECT * FROM foobar JOIN bar ON bar.id = foobar.bar_id LEFT JOIN fubar ON fubar.bar_id = bar.id WHERE foobar.status = 1 AND bar.status = 1 AND fubar.status = 1; As I look at each entry in the result set, I have all of the information to identify the FooBar, Bar, and Fubar records associated with each row. I can reproduce the same joins in Django: q = (FooBar.objects .filter(status=1, bar__status=1, bar__fubars__status=1) .select_related('bar')) If I iterate through the result set, I … -
How to read the events from ansible runner programatically
I use ansible runner to trigger an ansible-playbook from a django application, which runs fine. See the following code. import ansible_runner def runner(request): r = ansible_runner.run_async(private_data_dir='/Users/path/to/private_dir', playbook='path/to/provision.yml') What I am trying to do is provide a live update (The stdout of each of the ansible tasks running inside that playbook) to the user whenever a deployment is happening on his project. As of now, I can see the stdout instantly in the console. But I am not able to figure out how can I read the stdout interactively/instantly from ansible runner. I can wait for the task to finish and finally read the final stdout and display it to the user, which I think is not a better user experience. I would like to provide a live update on the play which is happening to the user. similar to you see on travis-ci builds. So far I am not able to figure out anything from the docs of ansible-runner. I tried inspecting the output of r.events like below r = ansible_runner.run_async(private_data_dir='/Users/path/to/private_dir', playbook='path/to/provision.yml') for event in r[1].events: try: print(event['event_data']['task']) except KeyError: pass # where r[1] is the Runner object returned by ansible, # r[0] is the thread which runs ansible so … -
'NoneType' object has no attribute '__dict__' with ModelForm and CreateView many to many relationship
I'm creating an instance of an application model and populating a new many to many table on form submission. When I submit the form, I receive a 'NoneType' object has no attribute 'dict' error. It seems to have something to do with get_success_url because the exception location is in \django\views\generic\edit.py in get_success_url but I am a beginner and am not sure what is happening because this is identical to another CreateView that works fine. Also, is this the proper way to create the new instance of the association table? Sorry, I'm sure this is a mess. views.py # The CreateView and success TemplateView class ApplicationView(LoginRequiredMixin, CreateView): form_class = ApplicationForm success_url = 'apply_success' template_name = 'apply.html' login_url = 'login' def form_valid(self, form): print(self.request.user.id) form.instance.applicant = self.request.user return super().form_valid(form) class ApplicationSuccess(TemplateView): template_name = 'application_success.html' # The ModelForm class ApplicationForm(forms.ModelForm): class Meta: model = Application fields = ['programs', ... ] labels = { 'session': 'What session are you most interested in?', ... } help_texts = { 'programs': 'Leave blank if there are no programs' } widgets = { 'programs': CheckboxSelectMultiple() } def save(self, commit=True): instance = forms.ModelForm.save(self, False) old_save_m2m = self.save_m2m def save_m2m(): old_save_m2m instance.programs.clear() for program in self.cleaned_data['programs']: instance.programs.add(program=program, school=request.user.mainschool) self.save_m2m = … -
how to use job_queue in django-telegrambot?
i am using python-telegram-bot and django-telegrambot. i set webhook and i want to use job_queue method to do a run_repeating for example but my code does not work. i dont know how to write it. thank you. def check_dollar_price(): r = requests.get('http://www.tgju.org/chart /price_dollar_rl').content from bs4 import BeautifulSoup soup = BeautifulSoup(r, 'html.parser') result = soup.find('div', {'class': "profile-container"}).ul.li.span.get_text() # bot = DjangoTelegramBot.dispatcher.bot bot = DjangoTelegramBot.dispatcher.bot bot.sendMessage(-1001326345035, 'the dollar price is >>> ' + result) def main(): logger.info(">>>>>>>>>secend app ================???? log") dp = DjangoTelegramBot.dispatcher jq = DjangoTelegramBot.dispatcher.job_queue jq.run_repeating(check_dollar_price, interval=60, first=0) -
Django index url is disabling api urls
integrating Angular with Django, server is receiving request from frontend but I can't handle them, because they doesn't reach target function here is views.py: class VView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def index(request): return render(request, 'index.html') @permission_classes((permissions.AllowAny)) class Login(APIView): def post(self, request) return JsonRespone({"some":"data"}, status=200) here are my urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url('', index), url('user/login',Login.as_view()), url('user/registration',Login.as_view()), ] and the thing is when send request now for user/login server doesn't respond with json as it should but when i comment out or delete my index url so I have: urlpatterns = [ url(r'^admin/', admin.site.urls), url('user/login',Login.as_view()), url('user/registration',Login.as_view()), ] everything works fine I get responses from server when I am using Postman for that, or run frontend on another localhost, but the problem is that server doesn't render webpage, when I access it by localhost:8000 -
translate caption of default Haystack form template
i want to translate the caption "Search In :" in default Django-Haystack Search form to frensh. thanks. -
Is there an equivalent for Rails' strong_params for Python/Django?
I'm currently trying to write a backend API built on Django. One thing I enjoy about Rails is I can easily control which parameters can be accepted via an HTTP request using the params.permit method. I was wondering if any of you knew of an equivalent for Django/Python? For example, in Ruby I can write the following in my Controller class: def user_params params.permit(:name) end So that the only editable params would be the name in a PUT action. If a dictionary with the key password was submitted, it would be automatically filtered out. I'd like to do something similar in my Django application, here's my views.py: def put(self, request): serializer = CustomUserSerializer() updatedUser = serializer.update(request.user, sanitizeProfileUpdate(request.data)) return Response('User Updated.') As of now, I can just strip the incoming data in the sanitizeProfileUpdate()method but I'd like to ideally do it before that. Thanks for the help. -
Django AJAX login without re-direct
Yes, there is a similar question without resolution to the actual question. My users may be trying out the app and then decide to register for an account to save. Once registered I need to log them in without redirecting or reloading the page. I've got the registration working and even logging them in no problem, but what do I return to the client in order for the logged in session to be active in the browser? I'm not looking to add any other frameworks or libraries to the stack, please. Django View (some omitted) class CheckAuthTokenAjaxView(FormView): form_class = AuthTokenForm def post(self, *args, **kwargs): form = self.form_class(self.request.POST) u = get_user_model().objects.filter(email=email).first() u.email_confirmed = True u.save() login(self.request, u) return JsonResponse({"success": True}, status=200) JS Doc.Register.checkAuthTokenForm = function(event) { event.preventDefault(); var form = document.getElementById('authtoken-form'); var data = new FormData(form); d3.json('/users/ajax/checkAuthToken/', { method: 'post', body: data, headers: { // "Content-type": "charset=UTF-8", "X-CSRFToken": Doc.CSRF, } }) .then(result => { if (result.hasOwnProperty('errors')) { // ... } else { // WHAT DO I DO HERE? } }); } -
How to use a async library in Django view?
I need to use a Python library that handles requests through the API of a web service. This library is an asyncio supported library. So I can't use it in a Django view by following the traditional and appropriate ways.. So what should I do to overcome this issue? I just thought that I can create a .py script and it would handle this library and I would use it in my Django view with os.system('...py') but it just looks awful. Could you help me to find a way that looks just "normal"? -
How to fix: http://localhost:8000/articles/update/1
I have a url problem when I click my update button it's sending me that url: http://localhost:8000/article/update/1 However, I must go that url: http://localhost:8000/articles/update/1 how can I solve this problem? urls.py //blog from django.contrib import admin from django.urls import path,include from article import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name="index"), path('about/', views.about, name="about"), path('articles/',include("article.urls")), path('user/',include("user.urls")), ] urls.py //articles from django.contrib import admin from django.urls import path from . import views app_name = "article" urlpatterns = [ path('dashboard/',views.dashboard,name="dashboard"), path('addarticle/',views.addarticle,name="addarticle"), path('article/<int:id>',views.detail,name="detail"), path('update/<int:id>',views.updateArticle,name="update"), ] -
Django-Rest-Api, connect model and api to multiple users
So I have a 'Notes' model, and I have UserProfile model (which is a user with some more info like age and description). Right now I can assign a note to a user, and only if I'm logged in to that user I will be able to see the API. Right now it's connected to a user via a Foreignkey. How do I connect a Note to multiple users? # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntegerField() description = models.CharField(max_length=300) class Meta: verbose_name_plural = 'User Profiles' def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_data(sender, update_fields, created, instance, **kwargs): if created: user = instance profile = UserProfile.objects.create(user=user, age=18, description='No Description') class Notes(models.Model): note = models.CharField(max_length=1000) parent_user = models.ForeignKey( UserProfile, blank=True, on_delete=models.CASCADE, related_name="notes" ) class Meta: verbose_name_plural = 'Notes' def __str__(self): return "{note}".format(note=self.note) views: # Create your views here. class NoteView(viewsets.ModelViewSet): http_method_names = ['get', 'post', 'put', 'delete', 'patch'] queryset = Notes.objects.all() serializer_class = NoteSerializer class UserNoteView(NoteView): def get_queryset(self): return self.request.user.userprofile.notes.all() # or return Notes.objects.filter(parent_user__user=self.request.user) -
Custom model field output formatting
I have a model: class Cat(models.Model): number = models.IntegerField(...) How can I modify the output so that when I call cat.number, I transform it into str, and add two zeros at the beginning? (12 -> "0012"). I cannot write a separate method/property to get this value, only number attribute of cat must be used. -
VariableDoesNotExist exception trying to customize Django auth's SetPasswordForm
Using Django (2.2) I am trying to customize the help text for the password1 field of the SetPasswordForm. The code that I have written to do this (check below) gives me an exception, which actually seems to be related to Django crispy forms. (I am using crispy forms with bootstrap4) I have gone over the code in the traceback, but figuring out that way what is happening exactly will be a hell of a job, so I am hoping someone more experienced can tell me what I am doing wrong here? traceback: Exception has occurred: VariableDoesNotExist Failed lookup for key [html5_required] in [{'True': True, 'False': False, 'None': None}, {'True': True, 'False': False, 'None': None, 'form': <CustomSetPasswordForm bound=False, valid=False, fields=(new_password1;new_password2)>, 'form_show_errors': True, 'form_show_labels': True, 'label_class': '', 'field_class': ''}, {'forloop': {'parentloop': {}, 'counter0': 0, 'counter': 1, 'revcounter': 2, 'revcounter0': 1, 'first': True, 'last': False}, 'field': <django.forms.boundfield.BoundField object at 0x7f8da9a43978>}, {}] File "/home/riksch/projects/youtube-content-request/venv/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup (bit, current)) # missing attribute File "/home/riksch/projects/youtube-content-request/venv/lib/python3.7/site-packages/django/template/base.py", line 796, in resolve value = self._resolve_lookup(context) File "/home/riksch/projects/youtube-content-request/venv/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/home/riksch/projects/youtube-content-request/venv/lib/python3.7/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/home/riksch/projects/youtube-content-request/venv/lib/python3.7/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/home/riksch/projects/youtube-content-request/venv/lib/python3.7/site-packages/django/template/base.py", line 937, in render bit … -
nginx ssl_certificate regex
when i use this code, i'm get error "No such file or directory" , but in docs writed what i can use variables server { listen 443 ssl; server_name ~^(?<sub>.+)\.domain$; ssl_certificate /etc/letsencrypt/live/$sub.domain/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/$sub.domain/privkey.pem; location /.well-known { alias /var/www/.well-known; } location / { proxy_pass http://$sub.domain:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } -
Make React-redux get all data from paginated backend
I have an application I've been developing for my company to convert data from an old system to a new one. It has a Django Rest Framework back end with a react / redux powered front end. Functionally the program does what I want it to, but it doesn't want to pull all the data. The back end API is paginated to a page size of 200. The front end has its own pagination so it doesn't show all ~40k results at once. I do however want it to load all of those results into the props so that it can be searched for the exact item they want. This may not be the best way to go about this problem, but it's my first full stack application so it will do for now. I have tried just removing the page size from the back end since none of my users will see it anyway. On smaller sets of data this worked fine. Once I started pulling from a larger data set however, it complains about the query parameters not matching what was expected for some reason unless I paginate. Here is the code I believe to be relevant. If … -
display list based on the conditional listview statement in django views using the same template
I want to display the list of requests based on a particular fruit of interest. so i wrote a list view with the condition that it should display list which includes mango otherwise, it should display list that includes banana. so when i render the template, the template should check if its mango_list or banana_list.but only mango_list displays. the else statement in views doesn't work i wrote the conditional statement in views to render mango_list if the context is mango_list else display banana_list. And put the condition in template. Here is my code below views.py def fruit_list_view(request): mango_list = Request.objects.filter(taste__icontains='mango') banana_list = Request.objects.filter(taste__icontains='banana') context ={ 'mango_list': mango_list, 'banana_list': banana_list, } if mango_list in context.values(): return render(request,"frCat_list.html",context={'mango_list': mango_list}) else: return render(request,"frCat_list.html",context={'banana_list': banana_list}) url.py urlpatterns = [ path('', views.index, name='index'), path('mango_list/', views.fruit_list_view, name='mango_list'), path('banana_list/', views.fruit_list_view, name='banana_list'), ] template file (template name is frCat_list.html) {% extends 'base_generic.html' %} {% load static %} {% block content %} <body> {% if mango_list %} {% for request in mango_list %} <tbody> <td><a href="{% url 'request-detail' request.id %}">{{request.id}}</a></td> <td>{{request.price}}</td> <td>{{request.size}}</td> <td>{{request.comment}}</td> </tbody> {% endfor %} </table> {% elif banana_list %} {% for request in banana_list %} <tbody> <td><a href="{% url 'request-detail' request.id %}">{{request.id}}</a></td> <td>{{request.colour}}</td> <td>{{request.size}}</td> <td>{{request.comment}}</td> </tbody> … -
django2 css sometimes not found produces 404 error
Using Django 2.2 (Ubuntu 19.04 and python3.7) and learning to add some css (and js) for the first time. Trying with a single app called homepage, to produce a visual homepage with three pages with some static. I get intermittent css 'file not found' 404 errors which I've been unable to resolve using many solutions listed in Django docs and on stackoverflow. I've followed django2.2 docs folder structure with app (homepage) under static/homepage each with its own folder and also tried:- a. Moving css, js, images folders to web1/static (global static) and to web1/static/homepage (no sub folders) b. using and adjusting STATIC_ROOT AND STATIC_URL to various settings c. adjusting static template tags using variations to match a. and with full url /web1/homepage/static/homepage/css without static tag d. with and without url + static[] stanza in urls.py e. css files with & without load static + tags f. reloaded and cleared caches, tried different browsers and machine. Project outline is :- ├── homepage │ ├── migrations │ │ └── __pycache__ │ ├── __pycache__ │ ├── static │ │ ├── admin │ │ │ ├── css │ │ │ ├── fonts │ │ │ ├── img │ │ │ └── js │ │ … -
Django REST Framework: URLs without PK
I'm using Django REST Framework with the HyperlinkedModelSerializer serializer.py: class ReportTypesViewSet(viewsets.ModelViewSet): queryset = ReportType.objects.all() serializer_class = ReportTypesSerializer api.py: class ReportTypesSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ReportType fields = ('name', 'uuid', 'active', ) Now the API works, but the hyperlinks have the pk within their URLs, such as: http://localhost:8000/api/reporttypes/1/ I would like to map the objects via the UUID field (which the model provides) rather than the internal PK. I know I could change the primary key to the UUID field, but I've read that would cause other issues, such as decreased performance. Is there a way I can reference the objects via the UUID, but still internally use the default pk (id)? -
A strange problem for a django project when make it online: pagination not working and sometimes result in 404 page not found
I made a searching website by Django and elasticsearch. It works fine in the local environment, then I push it to a ubuntu server and online it by gunicorn and ngnix. Everything is good except pagination: The first page is good, but when I required next page, sometimes it responses a 404 page not found. However, when I refresh it, sometimes it will display the right things. Also, sometimes it will give me the response page, but some content of the page is empty. Because I want to do the rank for the return items, I do those things for fast paging, don't know if it does matter: def get_context(self): global previous_results self.init_provterms() pool = ThreadPool(8) pool.map(self.init_rank, range(1, 8)) pool.close() pool.join() self.results = sorted(self.results, key=lambda result: result.object.Rank, reverse=True) previous_results = self.results (paginator, page) = self.build_page() if page.end_index() - page.number < 10: page_nums = range(page.number, page.end_index()) else: page_nums = range(page.number, page.number + 10) page.page_nums = page_nums save_query_form = SaveQueryForm(self.request.POST or None, initial={'Query_to_save': " ".join(self.request.GET.get('q', ''))}) saved_searches_list = saved_searches(self.request.user) context = { 'suggestions': list(sug), 'query': self.query, 'form': self.form, 'page': page, 'paginator': paginator, 'suggestion': None, 'weight': weight, 'save_form': save_query_form, 'saved_searches': saved_searches_list.items() } if hasattr(self.results, 'query') and self.results.query.backend.include_spelling: context['suggestion'] = self.form.get_suggestion() context.update(self.extra_context()) return context -
Changing django haystack search results accuracy for fixed keyword
I have set up a search functionality in my Django project with Django-Haystack and Elasticsearch, everything is working fine except for the accuracy of the results. Basically, I'm looking for a way to force the search results to only match the given Keyword and nothing else. The usecase is a user entering the destination where he is traveling to like Barcelona and get results only in that specific destination. But as of now, if I search the keyword Barcelona, I also get results from another destination like Dubai or Paris which is clearly non-acceptable for the user. Is there a way to do that? Here's my Haystack form: from haystack.forms import FacetedSearchForm class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.ptag = data.get('ptags', []) super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() # search filters if self.ptag: query = None for ptags in self.ptag: if query: query += u' OR ' else: query = u'' query += u'"%s"' % sqs.query.clean(ptags) sqs = sqs.narrow(u'ptags_exact:%s' % query) return sqs This is my Models: class Product(models.Model): destination = models.CharField(max_length=255, default='') title = models.CharField(max_length=255, default='') slug = models.SlugField(unique=True, max_length=255) description = models.TextField(max_length=2047, default='') link = models.TextField(max_length=500, default='') ptags = TaggableManager() image … -
How to fix mysqlclient 1.3.13 or newer is required you have 0.9.3
Ok so i want to connect my db with django, when i write a command : python managa.py migrate i have that error. How to fix it? [...] django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is requ ired; you have 0.9.3. -
Object of type datetime is not JSON serializable error
I have some issues with using a DateTime value in python. When I use session_start in the following code, I get an Object of type datetime is not JSON serializable error views.py dataSourceBar = {} dataSourceBar['chart'] = { "caption": "Rainfall", "subCaption": "Shown per date", "xAxisName": "Session", "yAxisName": "Rainfall in MM", "theme": "candy" } dataSourceBar['data'] = [] objects_with_category_id_2 = dashboard_input.objects.filter(category_category_id=2) for obj in objects_with_category_id_2: data = {'label': obj.session_start, 'value': obj.input_input_value} dataSourceBar['data'].append(data) model.py class dashboard_input(models.Model): session_start = models.DateTimeField(max_length=100) traceback Internal Server Error: /dashboard/ Traceback (most recent call last): File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\var\www\VSDK\vsdk\dashboard\views.py", line 69, in Chart return render(request, 'dash.html', {'output' : column2D.render(),'output2' : doughnut3d.render()}) File "C:\var\www\VSDK\vsdk\dashboard\fusioncharts.py", line 52, in render self.readyJson = json.dumps(self.constructorOptions, ensure_ascii=False) File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 238, in dumps **kw).encode(obj) File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Users\natas\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type datetime is not JSON serializable I retrieve the value from a database view which is filled by other … -
Button executing code before being pressed HTML
I have a html template which contains a button when u press the button it executes a function in views.py which i will list: from django.shortcuts import render from django.http import HttpResponse import requests from bs4 import BeautifulSoup def button(request): return render(request, 'home.html') def output(request): def trade_spider(max_pages): dat = '' page = 1 while(page <= max_pages): search = 'Ipad' url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=' + search + '&_sacat=0&_pgn=' + str(page) src = requests.get(url) text = src.text soup = BeautifulSoup(text, features="html.parser") for link in soup.findAll('a', {'class': 's-item__link'}): href = link.get('href') title = link.string if(title == None): title = "Sorry the title was unavailable however you can check the price." price = get_item_price(href) dat += href + '\n' + title + '\n' + price page+=1 return dat def get_item_price(item_url): src = requests.get(item_url) text = src.text soup = BeautifulSoup(text, features="html.parser") for item_price in soup.findAll('span', {'class': 'notranslate'}): price = item_price.string return price data = trade_spider(1) return render(request, 'home.html',{'data': data}) home.html: <!DOCTYPE html> <html> <head> <title> Python button script </title> </head> <body> <button>Execute Script</button> <hr> {% if data %} {{data | safe}} {% endif %} </body> </html> Everything works fine however when i run the page it diplays the button AND the output which i dont want … -
Django allauth adds social account to admin user
So whenever my user logs into their Shopify account, Django allauth adds the social account to the admin user. I used log statements and signals to debug. So I see that when the request is made for my application's homepage, the user id is 26 (which is a normal user). They are then redirected to login to Shopfiy. After they are authenticated, I see that the SocialAccounts database (from allauth) is updated with user 27 (which is the admin user). So the user was successfully able to authenticate with Shopify, but the social account is now associated with the admin. I have the following in my settings.py: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'layout/templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.request', ], }, }, ] INSTALLED_APPS = [ 'dal', 'dal_select2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.humanize', 'django.contrib.syndication', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.shopify', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', ] I would like the social account to be associated with the user that made the initial request.