Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix ValueError in pandas
I am moving an application from a classic Tkinter GUI to a Django cloud-based application and am receiving a ValueError: Invalid file path or buffer object type: <class 'bool'> when trying to run a function which calls on pandas. Exception Location: C:\Users\alfor\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\common.py in get_filepath_or_buffer, line 232 I have not tried much because I cannot find this same Error in searches. I do not believe this function even runs AT ALL because my media folder is not getting a new directory where the file would be saved.. but I could be wrong. The beginning of the function that is having issues looks like this: def runpayroll(): man_name = 'Jessica Jones' sar_file = os.path.isfile('media/reports/Stylist_Analysis.xls') sar_file2 = os.path.isfile('media/reports/Stylist_Analysis.xls') tips_file = os.path.isfile('media/reports/Tips_By_Employee_Report.xls') hours_wk1_file = os.path.isfile('media/reports/Employee_Hours1.xls') hours_wk2_file = os.path.isfile('media/reports/Employee_Hours2.xls') retention_file = os.path.isfile('media/reports/SC_Client_Retention_Report.xls') efficiency_file = os.path.isfile('media/reports/Employee_Service_Efficiency.xls') df_sar = pd.read_excel(sar_file, sheet_name=0, header=None, skiprows=4) df_sar2 = pd.read_excel(sar_file2, sheet_name=0, header=None, skiprows=4) df_tips = pd.read_excel(tips_file, sheet_name=0, header=None, skiprows=0) df_hours1 = pd.read_excel(hours_wk1_file, header=None, skiprows=5) df_hours2 = pd.read_excel(hours_wk2_file, header=None, skiprows=5) df_retention = pd.read_excel(retention_file, sheet_name=0, header=None, skiprows=8) df_efficiency = pd.read_excel(efficiency_file, sheet_name=0, header=None, skiprows=5) The only code I have changed from the rest of this function is this which I am assuming does not matter because it is only a file location.. writer = … -
Django create functions that can be used in several class
I have several classes where each class has its own function like routing, upload file, backup file, etc. each class has the same code line to connect to the device. I want to separate the lines of code into a separate class, so I just call it so this is my view.py file class config_static(View): ip_list = [] status = '' def post(self, request, *args, **kwargs): # if request.method == 'POST': formm = NacmForm(request.POST or None) ipform = IpFormset(request.POST) upform = UploadForm(request.POST,request.FILES) userValue = formm['username'].value() passValue = formm['password'].value() destination = str(request.POST['destination']) prefix = str(request.POST['prefix']) gateway = str(request.POST['gateway']) if ipform.is_valid() and formm.is_valid(): simpanForm = formm.save() for form in ipform: ipaddr = form.cleaned_data.get('ipaddr') vendor = form.cleaned_data.get('vendor') networks = str(destination+"/"+prefix) netmask = IPNetwork(networks).netmask collect_config = "<b>Configure on "+str(ipaddr)+" | vendor = "+str(vendor)+"</b></br>" try: ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=ipaddr,username=userValue,password=passValue,look_for_keys=False, allow_agent=False, timeout=5) remote_conn=ssh_client.invoke_shell() shell = remote_conn.recv(65535) config_read = str(vendor.sett_static_routing) array_read = config_read.split('\r') output_line = "" for line in array_read: new_line = re.sub(r'\n','',line) if new_line != '': config_send = eval(new_line) collect_config = collect_config + config_send+"</br>" print(config_send+" ini config send") try: stdin, stdout, stderr = ssh_client.exec_command(config_send+"\n") time.sleep(1) results = stdout.read() except: try: remote_conn.send(config_send+"\n") time.sleep(1) results = remote_conn.recv(65535) except: print("error paramiko") messages.success(request, collect_config) ssh_client.close() paramiko.util.log_to_file("filename.log") simpanIp = form.save(commit=False) … -
Ajax not appending HttpResponse from Django
The aim of my program is to take input from html page, send it to Django so the text turns upper case, and return a response so the page can display the uppercased text. There is no update to the page. Code on the html: <script> $("form").submit(function(e){ e.preventDefault(); val = $("#input").val(); $.ajax({ url: "{% url 'upper' %}", data: {'input':val}, success: function(data){ $('#result').append(data); } }); }); </script> Django's views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, "index.html", context = {"text": 'This is from Django'}) def upper(request): vals = request.GET.get('input') print(vals) return HttpResponse(vals.upper) -
using a group dynamically in Django
I have successfully created groups in Django dynamically and they are displaying in the Django-admin section but how can I access them dynamically throgh the webpage(in the website I'm creating)? Also I want to add users to that group and want to generate a list/table of users in that group. I cant find any clue on my problem. Please help. -
Show Total Retrieved Documents
I am using TF-IDF algorithm to retrieve the relevant documents with the query that i input. I have successfully retrieve the relevant documents, and show it too. But i want to show the TOTAL documents that has been retrieved. I am using this code to count the documents, but it show anything. {% for i in result %} {{i.pekerjaan.count}} {% endfor %} The result is like this picture below,that show NULL -
Does filter() throw an exception?
Does filter() throw an exception if there are no selected objects present in the database like get() or does it return None? I am having this code here: # Return a list of all chat posts attached to that chat_instance, if it exists. chat_posts_list = models.ChatPost.objects.filter(chat_instance=chat_instance) A ChatInstance can have zero or many ChatPosts, implying that for some certain cases, a specific ChatInstance may turn out to have no ChatPosts, so filter() will not return a full list. What will happen in that situation? Will filter() return None, or will it throw an exception? How should I handle that? -
Adding a file that stores images temporarily to my S3 bucket from my django project
Intro: I have a django web app that is hosted on AWS. Also my static and media files are stored on AWS S3. I have 2 buckets in my S3 namely Static and Media. Everything was working fine. Now I wanted to add a JavaScript library that reduces images on the client side and uploads the images to my media folder. I was able to do this successfully in the development stage. The catch: The JavaScript library uses a folder(I have named the folder filepond-temp-uploads) where it saves the images temporarily while the user is filling the form and when the form is submitted it saves it in the Media folder and deletes it from the filepond-temp-uploads folder This works perfectly in my development stage. Now in my production stage. The Static and Media folders are configured are configured correctly in my S3 (See code below) I need to know how to add filepond-temp-uploads folder to my S3 in my Django Settings File My Code: AWS_DEFAULT_ACL = None STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] DEFAULT_FILE_STORAGE = 'aws_storage_classes.MediaStorage' AWS_STORAGE_BUCKET_NAME = 'some_aws_busket_6d' STATICFILES_STORAGE = 'aws_storage_classes.StaticStorage' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_DOMAIN = "%s.s3.amazonaws.com" % AWS_STORAGE_BUCKET_NAME STATIC_URL = 'https://%s/static/' % AWS_S3_DOMAIN MEDIA_URL … -
Getting 403 error inspite of adding AWS static file-path to CORS_ORIGIN_WHITELIST django-cors-headers
I am using django-summernote to my text-field. This should make my text-field look somewhat like the image below Now the static files for the above above are stored in my AWS S3 bucket. I am getting a 403 error in the browsers console and below is how my text field looks like right now The 403 error in the console looks like below Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://some_bucket_66d.s3.amazonaws.com/static/summernote/font/summernote.woff?1d9aeaaff0a8939558a45be6cd52cd4c. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).[Learn More] downloadable font: download failed (font-family: "summernote" style:normal weight:400 stretch:100 src index:1): bad URI or cross-site access not allowed source: https://some_bucket_6d.s3.amazonaws.com/static/summernote/font/summernote.woff?1d9aeaaff0a8939558a45be6cd52cd4c So to solve this error I did pip install django-cors-headers Added INSTALLED_APPS = ( ... 'corsheaders', ... ] Added it to my middleware MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ... ] And added the below 3 links to my whitlist in my django settings. I don't know what http://127.0.0.1:9000 is for but I just let it be there anyways as it was in the https://pypi.org/project/django-cors-headers/ page CORS_ORIGIN_WHITELIST = [ "https://some_bucket_66d.s3.amazonaws.com", #This is the bucket path as you see in the error above "http://localhost:8080", "http://127.0.0.1:9000" ] I am still getting the same error what am I doing … -
Why do i keep getting a keyerror when assigning the first set of information to data variable to context?
Keep getting keyerror when trying to append a dictionary to a list in the context variable for get_context_data for django. players = Players.objects.all().order_by("user__last_name") for player in players: info = { 'Name': player.full_name, 'DOB': player.user.dob, 'Gender': player.user.gender, 'Team': 'Something', } context['data'].append(info) return context This is the error message i get, i've only changed the data in info for privacy reasons. __class__ <class 'Backend.views.AdminPlayersView'> context {'data': {}} count 0 info {'DOB': '2019-01-01', 'Gender': 1, 'Name': 'Name', 'Team': 'Something'} kwargs {} player <Players: Players object (240)> players <QuerySet [<Players: Players object (240)>, <Players: Players object (13)>, <Players: Players object (46)>, <Players: Players object (217)>, <Players: Players object (96)>, <Players: Players object (301)>, <Players: Players object (481)>, <Players: Players object (201)>, <Players: Players object (48)>, <Players: Players object (129)>, <Players: Players object (152)>, <Players: Players object (343)>, <Players: Players object (344)>, <Players: Players object (206)>, <Players: Players object (381)>, <Players: Players object (375)>, <Players: Players object (469)>, <Players: Players object (23)>, <Players: Players object (104)>, <Players: Players object (8)>, '...(remaining elements truncated)...']> self <Backend.views.AdminPlayersView object at 0x078118D0> -
How to fetch login endpoint and put token in headers in React?
I am trying to fetch my login API made in Django rest framework using React. How can I use token authentication with Django? How would you put the token in the headers, and would you have to get the token as a response? I have tried using postman, but I didn't know what the authentication was called. here are my authentication classes in my models. from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager Thank you in advance -
How to overwrite `id` as primary key with `timestamp` as primary key in django models?
I'm building a Django ETL engine that extracts data from GitHub using the enterprise API to gather metrics on internal company collaboration. I've designed some schema that I now realize won't scale due to the PK (primary key) that is automatically set by the ORM. One of the main features of the extraction is to get the id of the person that has created a repository, commented on a post, etc. My initial thought was to let the ORM automatically set the id as the PK but this won't work as the GET request is going to run once a week and it will raise errors causing the overwriting of the ID primary key to fail. I've done some research and one potential solution is to create a meta class as referenced here: Django model primary key as a pair but I am unsure if creating a few meta classes is going to defeat the entire point of a meta class to begin with. Here is the schema I have setup for the models.py from django.db import models from datetime import datetime """ Contruction of tables in MySQL instance """ class Repository(models.Model): id = models.PositiveIntegerField(null=False, primary_key=True) repo_name = models.CharField(max_length=50) creation_date … -
added button in table by jquery is not work
problom is that button in table added by jquery is not work original button <button class="btn btn-sm btn-warning float-right comment_delete_button" id="{{comment.pk}}">delete</button> <button class="btn btn-sm btn-info float-right comment_edit_button" id="{{comment.pk}}">edit</button> added button <button class="btn btn-sm btn-warning float-right comment_delete_button" id="<%= comment_id %>">delete</button> <button class="btn btn-sm btn-info float-right comment_edit_button" id="<%= comment_id %>">edit</button> I looked it up using f12 and it did not differ. But why is the event listener not working? $.ajax({ type: "POST", url: 'update_comment_ajax/'+id, data: { id:id, title:title, file_name:file_name, text:text, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(result) { alert('comment update complete '); } }); }); $(".comment_delete_button").click(function(e) { e.preventDefault(); var id = $(this).attr("id"); alert('삭제 id : ' + id); $.ajax({ type: "POST", url: 'delete_comment_ajax/'+id, data: { csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(result) { $("#comment_table_"+id ).remove(); alert('comment 삭제 complete '); } }); }); thanks for let me know how to fix it ~! -
Selenium unable to login to Django LiveServerTestCase
I'm struggling to get Selenium working with my Django project. I can (finally) get it to get pages during testing, but I'm unable to get it to login for some reason. This is my (very simple) test case: import pytest from django.conf import settings from django.contrib.auth import get_user_model from django.test.client import Client from pytest_django.live_server_helper import LiveServer from selenium.webdriver import Remote from users.tests.factories import UserFactory pytestmark = pytest.mark.django_db class TestDashboard: def test_site_loads(self, browser: Remote, test_server: LiveServer): browser.get(test_server.url) assert 'Welcome' in browser.title def test_valid_login(self, browser: Remote, test_server: LiveServer, user: settings.AUTH_USER_MODEL): password = 'testpassword' user.set_password(password) user.save() browser.get(test_server.url + '/accounts/login/') browser.find_element_by_name('login').send_keys(user.email) browser.find_element_by_name('password').send_keys(password) browser.find_element_by_css_selector('button[type="submit"]').click() browser.implicitly_wait(2) assert f'Successfully signed in as {user.username}' in browser.page_source test_site_loads passes, test_valid_login fails, and if I example browser.current_url it's still pointing at /accounts/login/. If I look at the page source using browser.page_source, I can see "The e-mail address and/or password you specified are not correct.". I have no idea why the login credentials are failing here. -
How to loop through list then return redirect
I am doing a file check by name after files are uploaded but the loop ends after the first file in the loop due to there being a return redirect if file exists. I have tried searching for similar issues to no avail. Likely due to not knowing how to word the question. def check_for_file(self): names = ['media/reports/Stylist_Analysis.xls', 'media/reports/Tips_By_Employee.xls', 'media/reports/Employee_Hours.xls', 'media/reports/Employee_Hours (1).xls', 'media/reports/Employee_Service_Efficiency_SC 8-10.xls', 'media/reports/SC_Client_Retention_Report.xls'] for name in names: if os.path.isfile(name): return redirect('landing') else: return redirect('blog-home') I would like it to loop over each file path and check if file exists. Once every file is confirmed I would like it to redirect. -
Filtering and pagination in Django 2x
It looks like the django-filter-mixin still has issues with Django 2x. So I'm trying to do it the 'old fashioned way'. The following starts with the filter criteria which works without fault, The pagination code is included but it is not working, I can't figure out if it's an issue with the view or the template (both included) views.py def allcontainer(request): allcontainer = Container.objects.all() container_list = Container.objects.all() user_list = User.objects.all() type = request.GET.get('type') name = request.GET.get('name') rack = request.GET.get('rack') shelf = request.GET.get('shelf') if ( type =='' or type is None and name =='' or name is None and rack =='' or rack is None and shelf =='' or shelf is None ): allcontainer = allcontainer if type !='' and type is not None: allcontainer = allcontainer.filter(container_type__iexact=type) if name !='' and name is not None: allcontainer = allcontainer.filter(container_name__iexact=name) if rack !='' and rack is not None: allcontainer = allcontainer.filter(location_id__location_name__iexact=rack) if shelf !='' and shelf is not None: allcontainer = allcontainer.filter(location_id__location_sub_name__iexact=shelf) qs = allcontainer paginator = Paginator(qs, 25) page = request.GET.get('page') try: pub = paginator.page(page) except PageNotAnInteger: pub = paginator.page(1) except EmptyPage: pub = paginator.page(paginator.num_pages) # url_filter = PublicationFilter(request.GET, queryset=qs) context = { 'container':allcontainer, 'type': type, 'pub':pub, # 'url_filter':url_filter # name # … -
I'm receiving a 408 error after deploying an Elastic Beanstalk app over https
I setup the certificate, opened the ports and configured django to reply over https in an EBS app. However, when accessing using https I receive a 408 timeout error. Http access works normally. How can I get https to work? -
Ordering of objects in list_field in Django 2.2.1
I just upgraded a project from Django 1.11.20 to Django 2.2.1 and noticed that the order in my list_filter:s was a bit random. Has the ordering my the Model's ordering-property been removed in later (than 1.11.20) Django versions? I took a look at the queries and this is the query for getting Customers in the RelatedOnlyFieldListFilter filter in Django 2.2.1: SELECT `core_customer`.`id`, `core_customer`.`name`, `core_customer`.`organization_number`, `core_customer`.`disable_auto_creation_of_invoices` FROM `core_customer` WHERE `core_customer`.`id` IN (SELECT DISTINCT U0.`customer_id` FROM `time_report_timereportentry` U0) And this is the query in Django 1.11.20: SELECT `core_customer`.`id`, `core_customer`.`name`, `core_customer`.`organization_number`, `core_customer`.`disable_auto_creation_of_invoices` FROM `core_customer` WHERE `core_customer`.`id` IN (SELECT DISTINCT U0.`customer_id` AS Col1 FROM `time_report_timereportentry` U0) ORDER BY `core_customer`.`name` ASC As you can see there's an ORDER BY in Django 1.11.20, but it's missing in Django 2.2.1. Do you have any ideas on how to get the objects sorted by the ordering-property? And it seems like a normal list_filter (without RelatedOnlyFieldListFilter) also doesn't order by the ordering property. Thanks for any help. -
Django firebase authentication flow
I am writing a mobile app and need validation of my understanding how a proper auth flow works (Firebase auth and Django backend): 1. Client (app user) signsup/in, Firebase returns a tokenID 2. Client sends tokenID to backend server 3. Server verifies tokenID with firebase, which in response returns the user_id 4. Server now has verified and identified client and generates a cookie, to be passed in every request by the user. If I got that right, how long should the cookie last before the client has to get another tokenID from Firebase? What's best security wise but viable for a production app in terms of speed? I lack the theoretical background and need some guidance here. -
TabError: inconsistent use of tabs and spaces in indentation - Integration MailChimp Django
I have just integrated Mailchimp to my Django Project using Ajax. The email address field is working properly and I'm able to get the email in both my Mailchimp list and my database. Now when I try to add a field that let a user add his first name to the form, I keep getting errors like this one for example: from .utils import SendSubscribeMail File "C:\Users\locq\Desktop\Coding\SEARCH_APP\venv\src\search\utils.py", line 8 self.fname = fname ^ TabError: inconsistent use of tabs and spaces in indentation.. So how can I add a FNAME field and send the datas to mailchimp on submit? Here's my code: In my Settings.p I added my Mailchimp credentials at the bottom like this: MAILCHIMP_API_KEY = '767ba************-us6' MAILCHIMP_SUBSCRIBE_LIST_ID = '45c*******' I created a utils.py file to use Threading, the Mailchimp package and import my credentials from the settings: import threading import mailchimp from django.conf import settings class SendSubscribeMail(object): def __init__(self, email, fname): self.email = email self.fname = fname thread = threading.Thread(target=self.run, args=()) thread.daemon = True thread.start() def run(self): API_KEY = settings.MAILCHIMP_API_KEY LIST_ID = settings.MAILCHIMP_SUBSCRIBE_LIST_ID api = mailchimp.Mailchimp(API_KEY) try: api.lists.subscribe(LIST_ID, {'email': self.email}, merge_vars={'FNAME': self.fname}, double_optin=False) except: return False Custom Def to get the input names: def subscribe(request): if request.method == 'POST': … -
Does it make sense to use nosql databases with Django ORM?
I have being using Django for a while, along with PostgreSQL, and I have to say that Django's address of relational databases features through its ORM is fantastic. It is very intuitive and reduces the development time a lot. I basically have stoped using SQL at all. Now I am starting to explore database paradigms others than relational, mainly nosql and graph databases, and I have found that there are several libraries that allow Django to interact with these database models. The problem is that I found that, to force these database models into Django, basically implies that you are giving up their special features that differentiate them from relational databases in order to allow Django to be able to deal with them. For example, one of the main features of nosql databases is that they are schemaless, which means that objects of the same type don't require to have the same fields but, when you use Django, all you get is a translator that converts sql sentences to nosql instructions, and, in the end, you define fixed models that represent database objects. Another example is with graph databases, that are supposed to dynamically relate objects through relationships that might … -
How to upload image from Angular to Django (Rest Framework) within nested model?
I am relatively new to Django.. I am Trying to upload images to a model (one-to-many) from Angular Front-End. I have tried several different attempts but for some reason the response is returning an empty image. I am getting a success response but the Image is not being saved, rather its value is {}. I have a model for which the user can upload one or more images. So I created a separate Image class and established a one-to-many relationship between my main model and the image class. Since I am dealing with a nested serializer class, I had to create a custom 'create' method for POST-ing a new entry. I created a ViewSet for the image class and POST-ed an image there by adding an image model entry directly. That worked fine. But getting {} for when POST-ing a nested object for which one the fields is the image instance. Djano Image Class class MetalComponentImage(models.Model): prong = models.ForeignKey(Prong, related_name='images', on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to='component-images', null=True, blank=True) isMain = models.BooleanField() Djano Nested Object class Prong(MetalComponent): metalComponentType = models.CharField(max_length=30, choices=MetalComponentTypeChoices.choices(), null=True) Typescript Nested Object & Image Classes export class MetalComponent{ metalComponentType : ComponentType; id: number; images?: MetalComponentImage[] = [];} export class … -
Accessing model manager methods in Django admin form
Say that I have the following Django model + manager which, as a simple example, represents the two parts of an email address: class ExampleModelManager(models.Manager): def from_addr(self, addr): name, domain = addr.split("@") m = self.create(name=name, domain=domain) return m class ExampleModel(models.Model): name = models.CharField(max_length=32) domain = models.CharField(max_length=32) objects = ExampleModelManager() This allows creation like: >>> ExampleModel.objects.from_addr("user@example.com") Now, I would like to mimic this in the admin's form: have just 1 form field there, "Address," rather than the default ("Name" + "Domain"); take the form input and call ExampleModel.objects.from_addr() to create and save the model instance. What is the conventional way to do this? Current solution: I'm able to do this by subclassing ModelForm and overriding its save(), basically writing the same logic and duplicating code. This seems like a lot of work, mimicking the logic of from_addr() in the method of another class: class ExampleForm(forms.ModelForm): addr = forms.CharField() def save(self, commit=True): addr = self.cleaned_data.get("addr") instance = super().save(commit=commit) instance.name, instance.domain = addr.split("@") if commit: instance.save() return instance class Meta: model = ExampleModel fields = "__all__" @admin.register(ExampleModel) class ExampleModelAdmin(admin.ModelAdmin): form = ExampleForm fields = ("addr", "name", "domain") readonly_fields = ("name", "domain") But I'm wondering if I could (and should) just access the manager … -
Serializing to custom nested dict
First, I think it's important to show some code to help to understand what I'm trying to achieve. Here goes my serializers: class ExerciseRoutineSerializer(serializers.ModelSerializer): exercise = ExerciseSerializer() class Meta: model = ExerciseRoutine fields = '__all__' def to_representation(self, obj): representation = super().to_representation(obj) exercise_representation = representation.pop('exercise') for key in exercise_representation: representation[key] = exercise_representation[key] return representation class RoutineSerializer(serializers.ModelSerializer): exercises = ExerciseRoutineSerializer(many=True) class Meta: model = Routine fields = '__all__' Basically, what I need, it to have exercises field in RoutineSerializer in some ordered data structure. Currently, this is my output: [ { "id": 1, "routines": [ { "id": 1, "exercises": [ { "id": 1, "index": 0, "rest_time": 60, "repetition_goal": 10, "equipment": [ { "id": 1, "equipment": "Fixed Bar" } ], "name": "Pull up" } ], "name": "RoutineName", "routine_type": "Regular" } ], "name": "WorkoutName" } ] It's returning the exercises according toExerciseRoutineSerializer, which is great. However, as I needed them ordered, I created an 'index' field in the model that takes charge of the order of it. is something like this: [ { "id": 1, "routines": [ { "id": 1, "exercises": { 0 : {"id": 1, "rest_time": 60, "repetition_goal": 10,"equipment": [{..}], "name": "Pull up"}, 1 : {"id": 13, "rest_time": 60, "repetition_goal": 10,"equipment": [{..}], "name": … -
How to use an HTML form user input in a python function
So I'm working in developing a web page to my project, so my question is, given user input in the html form, how can I use that input to call a python function (the function receives the string as a parameter). Keep in mind that I'll be using Django to run everything when I'm done with this. Following with the html form I'm currently using (I'm really new to html, so any feedback is welcome). <form> Sequente:<br> <input type="text" name="sequente", placeholder="a,f,a- >b,b->c,c->d,d->e|-e", method = 'get'> <br> <input type="submit" value="submit"> </form> -
How To Correctly Combine Django-Allauth and Custom User Profile App?
I've created a new app called users with the model Profile. For authentication I'm using django-allauth with Facebook and Google providers. Once user is logged in, I'd like to create a profile with some additional information populated from social providers, like: full_name, email, picture. Here is what I have in the models.py: from django.contrib.auth.models import User from django.dispatch import receiver from allauth.account.signals import user_signed_up class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(default=None, max_length=255) email = models.CharField(default=None, max_length=500) picture = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return self.user.username @receiver(user_signed_up) def populate_profile(sociallogin, user, **kwargs): user.profile = Profile() if sociallogin.account.provider == 'facebook': user_data = user.socialaccount_set.filter(provider='facebook')[0].extra_data picture_url = "http://graph.facebook.com/" + sociallogin.account.uid + "/picture?type=large" email = user_data['email'] full_name = user_data['name'] if sociallogin.account.provider == 'google': user_data = user.socialaccount_set.filter(provider='google')[0].extra_data picture_url = user_data['picture'] email = user_data['email'] full_name = user_data['name'] user.profile.picture = picture_url user.profile.email = email user.profile.full_name = full_name user.profile.save() While logging with Facebook, I'm getting the following error message: IntegrityError duplicate key value violates unique constraint "users_profile_user_id_key" And when I try to log in with Google, I receive the following: DataError at /accounts/google/login/callback/ value too long for type character varying(100) Can someone please tell me what's wrong with my code? Thanks in advance.