Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Build a Third Party API Using Django
I am interested in building a third party software to provide service through API. But the problem is I don't have any in depth knowledge related to this (i.e how am I suppose to count the api calls, where I will store the data from both side like this) Can someone suggest me some resources that will help me to go through this. Thank you! -
allauth urls are not accessible - 404 error
Can someone please help to solve my issue. Thanks in advance when i try to access 'accounts/' in django,then causing 404 error. I'm using allauth. URL Trying to access : http://127.0.0.1:8000/accounts/ URL's below are showing errors: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/ Using the URLconf defined in videoservice.urls, Django tried these URL patterns, in this order: admin/ accounts/ ^ ^signup/$ [name='account_signup'] accounts/ ^ ^login/$ [name='account_login'] accounts/ ^ ^logout/$ [name='account_logout'] accounts/ ^ ^password/change/$ [name='account_change_password'] accounts/ ^ ^password/set/$ [name='account_set_password'] accounts/ ^ ^inactive/$ [name='account_inactive'] accounts/ ^ ^email/$ [name='account_email'] accounts/ ^ ^confirm-email/$ [name='account_email_verification_sent'] accounts/ ^ ^confirm-email/(?P<key>[-:\w]+)/$ [name='account_confirm_email'] accounts/ ^ ^password/reset/$ [name='account_reset_password'] accounts/ ^ ^password/reset/done/$ [name='account_reset_password_done'] accounts/ ^ ^password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(? P<key>.+)/$ [name='account_reset_password_from_key'] accounts/ ^ ^password/reset/key/done/$ [name='account_reset_password_from_key_done'] accounts/ ^social/ ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ The current path, accounts/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Problem to run a check in my database in django
I have created a model called Certs, the models is registered and it is showing in the admin page, however I am trying to call it to run a check and try to make a task, but I am getting the error: No module named 'ships', This is the structure of my project (note I am writing the code in reminders.py): And here my code: from django.core.mail import send_mail from ships.models import Certs from datetime import datetime, timedelta b = Certs.objects.count() def notifications(): for dates in range(b): if Certs.exp_date[b] <= datetime.datetime.now() - timedelta(days=30): send_mail(subject='Test',message='This is a reminder where you will be reminded about expiring certifications', recipient_list=['info@intermaritime.org']) Thank you very much -
How can I upload file using DRF in my own custom html template?
class Contents(models.Model): name = models.CharField(max_length=100) formula = models.CharField(max_length=20) description = models.TextField(null=True, max_length=100) wiki = models.CharField(null=True, max_length=100) youtube = models.CharField(null=True, max_length=100) file = models.FileField() def __str__(self): return self.name this is my models.py class ContentsListCreateAPIView(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'admin3.html' style = {'template_pack': 'rest_framework/vertical/'} def get(self, request): queryset = Contents.objects.all() serializer = ContentsSerializer return Response({'serializer': serializer, 'contents': queryset, 'style': self.style}) def post(self, request): queryset = Contents.objects.all() serializer = ContentsSerializer(data=request.data) print(serializer.is_valid()) print(serializer.data) if serializer.is_valid(): serializer.save() return redirect('contents_list') return redirect('contents_list') views.py from rest_framework import serializers from .models import Contents class ContentsSerializer(serializers.ModelSerializer): class Meta: model = Contents fields = '__all__' serializers.py <form action="{% url 'contents_list' %}" method="POST"> {% csrf_token %} {% render_form serializer %} <input type="submit" value="Save"> admin.html It seems that the filefield does not get the proper input. I don't get what the problem is. The CreateAPIView works well when I use the default DRF template. -
Modelform: Missing Manytomany field in cleaned_data
I've got all the fields needed in the form.cleaned_data dict except one field is missing, the manytomany field. It's in form.data though. models.py class Tags(models.Model): tagtext = models.CharField(max_length=20) class Taggeditems(models.Model): name = models.CharField(max_length=20) tags = models.ManyToManyField(Tags, related_name='item_with_this_tag') forms.py class TaggeditemsForm(forms.ModelForm): name = forms.CharField(max_length=200,required=True) tags = tag_fields.TagsInputField(queryset=Tags.objects.all(), create_missing=True, required=False) class Meta: model = Taggeditems fields = '__all__' widget= { 'tags': tag_widgets.TagsInputWidget, } views.py if request.method == 'POST': f = TaggeditemsForm(request.POST) if f.is_valid(): if 'new' in request.GET.keys(): saved_taggeditem = f.save(commit=False) saved_taggeditem.save() saved_taggeditem.tags.set(f.cleaned_data["texttags"]) f.save_m2m() ... else: f = TaggeditemsForm(request.user, request.POST) ... I'm using an app django-tag-input for the display of the tag by the way. So I've got, when posting, the field tags in f.data but it's missing in f.cleaned_data (whereas the field name is present in both f.data and in f.cleaned_data). -
Creating a AP quiz using Django involving HTML
I currently use Django 3.1.2 and Python 3.7. I have a problem with creating the quiz below. Here's my code: views.py from django.shortcuts import render from django.http import HttpResponse from django.template import loader from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from .models import Question from .models import Answer #from .models import Answer # Create your views here. def index(request): return render(request, 'apquiz/index.html') #print(request.POST) def question(request): template = loader.get_template('apquiz/hi.html') questions = ["1. What is Dosie's position in PURPLE KISS?", "2. Yuki's position in PURPLE KISS, based on this excerpt is:","3. PURPLE KISS has how many members:","4. PURPLE KISS debuted on","5. Which of the following is PURPLE KISS's main vocalist?"] answers = [{'a. main rapper, main dancer, vocalist':0,'b. lead dancer, lead rapper':0, 'c. main dancer, vocalist':1,'d. main dancer, lead rapper':0},{'a. lead dancer, vocalist, rapper, visual':0,'b. lead rapper, lead dancer, vocalist, visual':0, 'main rapper, lead dancer, vocalist, visual':1, 'd. main vocalist, lead dancer, rapper, visual':0},{'a. 7':1,'b. 2':0,'c.9':0,'d.2':0}, {'a. August 3, 2020':0,'b. March 15, 2021':1, 'c. February 3, 2021':0,'d. November 26, 2020':0},{'a. Yuki':0,'b. Dosie':0,'c. Jieun':0,'d. Swan':1}] #questions = Question.objects.get() #answers = Answer.objects.get() print(questions) print(answers) context = {} numberofquestions = len(questions) numberofcorrectanswers = 0 for i in questions: … -
how to File upload in graphene django
hello i wanted to upload images and files in graphene , i am bit confused here in what i want to do... here is my code below seems like its not working i installed package graphene file upload schema.py class Users_Type(DjangoObjectType): class Meta: model = Users fields = '__all__' class Users_mutation(graphene.Mutation): class Arguments: name = graphene.String() password = graphene.String() image = Upload() users = graphene.Field(Users_Type) def mutate(cls,info,name,image,password): user = Users(username=name,password=password,user_profile=image) user.save() return Users_mutation(users=user) Under main mutation class create_user = Users_mutation.Field() my main goal is to upload files and images , pls tell me how to do it and neccassary string that need to be put in mutation... Help would be appreciated -
Customise JWT auth-token generation using user_id and otp as input
I have a system that uses 'mobile_number' and 'otp' for login. For the purpose I have create the first api that accept the mobile number and returns the user details. Otp generation and sending is done in the sane api. I want to create the togen-generation api, and the api accepts 'user_id' and 'otp'. Models: class User(AbstractUser): password = models.CharField(max_length=128, blank=True, null=True) email = models.EmailField(max_length=254, unique=True) dial_code_id = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100, blank=True, null=True) username = models.CharField(max_length=150, unique=True, blank=True, null=True) is_resource = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) skills = models.ManyToManyField(Skills) class Meta: db_table = "my_user" def __str__(self): return self.mobile_number class Otp(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) otp = models.IntegerField() created_on = models.DateTimeField(default=timezone.now()) class Meta: db_table = "otp" I have done the Token generation using https://django-rest-framework-simplejwt.readthedocs.io/en/latest/ but the below endpoint, path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), it accepts username and password for token generation. I am a beginner to django-rest and I want your help for the customisation. -
How to get square box to dropdown list in javascript
A square box of color corresponding to each condition is output, not a value in the column. And I am using Datatable jquery, in the dropdown list of the column I want a square box of three colors to be printed. (So the goal is to only see the green square box when you select the green square box.) $(this).val() -> Should I change this part? <td> <div> {% if alpha == 'A' %} <div class="square-box green"></div> {% elif alpha == 'B' %} <div class="square-box gray"></div> {% elif alpha == 'C' %} <div class="square-box yellow"></div> {% endif %} </div> </td> $(document).ready(function() { $('#table').DataTable( { initComplete: function () { this.api().columns().every( function () { var column = this; var colTitle = this.header().innerHTML; var select = $('<select><option class="" selected>' + colTitle + '</option></select>') .appendTo( $(column.header()).empty() ) .on( 'change', function () { var val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search( val ? '^'+val+'$' : '', true, false ) .draw(); } ); column.data().unique().sort().each( function ( d, j ) { select.append( '<option>'+d+'</option>' ) } ); } ); } } ); } ); -
Django saml2 login missing session variables
For my Django application, I am trying to enable SSO using Djangosaml2 and following are the versions I am using djangosaml2==1.2.0 pysaml2==7.0.0 djangorestframework==3.12.2 Django==3.1.7 python==3.8 My saml2_settings is as follows from os import path import saml2 import saml2.saml from app.local_settings import SERVER_URL AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'djangosaml2.backends.Saml2Backend', ) SAML_SESSION_COOKIE_NAME = 'saml_session' SAML_ATTRIBUTE_MAPPING = { 'username': ('username', ), 'email': ('email', ), 'first_name': ('first_name', ), 'last_name': ('last_name', ), } BASEDIR = path.dirname(path.abspath(__file__)) SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' LOGIN_URL = '/saml2/login/' LOGOUT_URL = '/saml2/logout/' SESSION_EXPIRE_AT_BROWSER_CLOSE = True SAML_CREATE_UNKNOWN_USER = True SAML_SERVER_URL = '10.23.1.114' SAML_ENABLED = True # MIDDLEWARE.append('djangosaml2.middleware.SamlSessionMiddleware') SAML_CONFIG = { # full path to the xmlsec1 binary programm 'xmlsec_binary': '/usr/bin/xmlsec1', # your entity id, usually your subdomain plus the url to the metadata view 'entityid': path.join(SAML_SERVER_URL, 'saml2/metadata'), # directory with attribute mapping 'attribute_map_dir': path.join(BASEDIR, 'attribute_maps'), # this block states what services we provide 'service': { # we are just a lonely SP 'sp' : { 'name': 'Dummy app', 'allow_unsolicited': True, 'authn_requests_signed': True, 'force_authn': True, 'want_response_signed': True, 'want_assertions_signed': True, 'logout_requests_signed': True, 'name_id_format_allow_create': False, 'endpoints': { # url and binding to the assetion consumer service view # do not change the binding or service name 'assertion_consumer_service': [ (path.join(SAML_SERVER_URL, 'saml2/acs/'), saml2.BINDING_HTTP_POST), ], # url and binding to … -
what is difference b/w django-admin startapp vs python manage.py startapp?
both does the same job creating the app in projects what the different between these two in Django? -
Saving data from a dynamically generated HTML table/grid to a database
I'm developing a web application and one of the requirements is for the user to enter data into a dynamically-generated HTML grid/table. An admin user can log into the Django Admin interface and create some entries which will represent the columns and rows of the grid, and then a dynamic grid is genereted based on these values. In this example, the admin user has entered "Store #1", Store #2", etc as the rows, and "Chips", "Chocolates", and "Soda" as the columns. These rows and columns are then used to generate a grid which is rendered in a Django template by the code below: <table class="tg"> <thead> <th rowspan="3"></th> <tr> <td class="tg-title" colspan="4">Inventory</td> </tr> <tr> {% for i in items %} <td class="tg-column">{{ i }}</td> {% endfor %} </tr> </thead> <tbody> {% for i in stores %} <tr> <td class="tg-column">{{ i }}</td> {% for i in items %} <td class="tg-cell"><input type="number" min="0" max="255" value="0"></td> {% endfor %} </tr> {% endfor %} <tr> <td class="tg-totals">Totals</td> {% for i in items %} <td class="tg-totals-values">0</td> {% endfor %} </tr> </tbody> </table> The above code renders like this: rendered_image Visually, this is fine, but I can't for the life of me figure out how I'm … -
When click a link in a link list generated by for loop, make the corresponding checkbox checked instead of the first checkbox
I have used Django to develop a web app. The front end used Django template engine. In the HTML, a link list is generated by a for loop, before which a check box is shown corresponding to this link. I want to achieve this: when click the link, the corresponding checkbox would be checked. But now as I only has one id(in the loop I do not know how to generate different id in one line), o matter I click which link generated by the loop, always see the first checked box checked instead of the corresponding one. HTML: <td>{% for course_for_select in query_results_2 %} &nbsp;<input type="checkbox" name="course_select" value=" {{course_for_select}}" id="addModal-body">&nbsp;<a href="#" name="course_select_2" id="href_course" onclick="document.getElementById('addModal-body').checked = true;this.closest('form').submit();return false;">&nbsp; {{course_for_select}}</a><br> {% endfor %}</td> How to let the corresponding checkbox checked after click the link behind, instead of constantly see the first one being checked? -
How to count video views for each user in django
In my recent project i want users to be able to see the number of videos they have watch. Like Total views today: Total views yesterday: Total views this month All time total views: I want all of this information in the user dashboard. I know how to get a total number of views on a video. But how do i make the video view count for each specific user. That when the user watchs a video on the website it counts as one in his or her dashboard..am using python and django. Any idea on how i can do this? -
Django- how to hyphenate TextField in URLs
I am trying to make my model so that the URL slug is hyphenated between spaces in the slug field by default. The slug should be limited to only the first six words in TextField. The TextField() called questionToProblem in the same model. Here's what I have: class Problem(models.Model): free = models.CharField(max_length = 1, choices = Free) questionToProblem = models.TextField() solutionToProblem = models.TextField() slug = models.CharField(max_length = 250, unique = True) topic = models.ForeignKey(Topic, on_delete = models.CASCADE) plainText = models.TextField(default= 'temp') class Meta: ordering = ('questionToProblem',) def get_url(self): return reverse('solution_details', args = [self.topic.slug, self.slug]) def __str__(self): return self.questionToProblem Ideally, here's what I want the URL to look like, if the questionToProblem was "How many bananas do I have in total?", and the Topic key was "modeltopic": http://127.0.0.1:8000/modeltopic/How-many-bananas-do-I-have -
I want to keep a long process running in the background in django
I am a beginner in django. I want to keep running long processes in django in the background. And I want to keep it running unless I explicitly end that process. I can't figure out where and how to add the following code to django. import threading import asyncio class long_task: def __init__(self): self.continue_flag = True async def long_task(self,): print('long task start...') i = 0 while self.continue_flag: print(i) await asyncio.sleep(3) i = i+1 def stop(self): self.continue_flag = False def run_loop(loop): asyncio.set_event_loop(loop) print('main loop start...') loop.run_forever() def ask_loop_stop(loop): print("main loop stop") loop.call_soon_threadsafe(loop.stop) loop = asyncio.get_event_loop() threading.Thread(target=run_loop, args=(loop,)).start() print('main loop is ready') long_task_1 = long_task() asyncio.run_coroutine_threadsafe(long_task_1.long_task(), loop) I will elaborate on what I want to do. Run a loop when django starts. Add long_task to the loop at any given time (when a specific event occurs by monitoring an external site). Keep the program running in the background so that the site can be viewed. In the future I would like to display the results of this program on a page. Close the loop at another time (during maintenance). Here's what I've tried Register and execute as a task using celery and celery-beat. => Can't specify that a program should be run … -
check many to many field exists in parent class
this is my blog model class Blog(models.Model): title = models.CharField(max_length=80, blank=True, null=True) content = models.TextField(blank=True, null=True) pricing_tier = models.ManyToManyField(Pricing, related_name='paid_blogs', verbose_name='Visibility', blank=True) I want to create a notification with post save signal if pricing tier has free-trial slug exists, so I tried as follows def blog_notify_receiver(sender, instance, created, *args, **kwargs): if created and instance.pricing_tier.filter(slug='free-trial').exists(): try: BlogNotification.objects.create() except: pass post_save.connect(blog_notify_receiver, sender=Blog) this doesn't work as it always gives none, the following print shows empty queryset, eventhough the data exists in the pricing tier field if created: print(instance.pricing_tier.all()) How I can check if data exixts in the pricing tier field which is a many to many field of a parent class -
How to get Authorization token in views.py (DRF)
class RecordDetailView(generics.RetrieveAPIView): serializer_class = RecordsSerializer permission_classes = [IsAuthenticated] lookup_url_kwarg = 'pk' def get(self, request, format=None, *args, **kwargs): item = request.GET.get(self.lookup_url_kwarg) token = request.META.get('HTTP_AUTHORIZATION') print("token", token) user_from_token = Token.objects.filter(key=token).first() record = Records.objects.filter(id=item).first() if record.author.username != user_from_token.user.username: return Response({'response': "You dont have permission to view that"}, status=status.HTTP_403_FORBIDDEN) else: data = get_object_or_404(Records, id=item) return Response(data, status=status.HTTP_200_OK) i tried to get the data from postman and i filled authorization field in headers with the user token and I'm trying to print the token in my views but it returns None, Any idea how to get the token -
Download image on heroku
i have a simple function in fastapi python url="some_random_video_url_here" re = requests.get(url) with open("download/hello.png", 'wb') as file: #save hello.png to download folder file.write(re.content) file.close() this function work locally fine and download image and any files bot when upload on heroku not download image and save in staticsFiles folder please help -
Struggling to deploy django project on heroku
Build log: -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt -----> Requirements file has been changed, clearing cached dependencies -----> Installing python-3.9.5 -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 -----> Installing SQLite3 -----> Installing requirements with pip Collecting asgiref==3.3.4 Downloading asgiref-3.3.4-py3-none-any.whl (22 kB) Collecting boto3==1.17.79 Downloading boto3-1.17.79-py2.py3-none-any.whl (131 kB) Collecting botocore==1.20.79 Downloading botocore-1.20.79-py2.py3-none-any.whl (7.6 MB) Collecting dj-database-url==0.5.0 Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) Collecting Django==3.2.3 Downloading Django-3.2.3-py3-none-any.whl (7.9 MB) Collecting django-environ==0.4.5 Downloading django_environ-0.4.5-py2.py3-none-any.whl (21 kB) Collecting django-on-heroku==1.1.2 Downloading django_on_heroku-1.1.2-py2.py3-none-any.whl (6.1 kB) Collecting gunicorn==20.1.0 Downloading gunicorn-20.1.0-py3-none-any.whl (79 kB) Collecting jmespath==0.10.0 Downloading jmespath-0.10.0-py2.py3-none-any.whl (24 kB) Collecting psycopg2==2.8.6 Downloading psycopg2-2.8.6.tar.gz (383 kB) Collecting psycopg2-binary==2.8.6 Downloading psycopg2_binary-2.8.6-cp39-cp39-manylinux1_x86_64.whl (3.0 MB) Collecting python-dateutil==2.8.1 Downloading python_dateutil-2.8.1-py2.py3-none-any.whl (227 kB) Collecting pytz==2021.1 Downloading pytz-2021.1-py2.py3-none-any.whl (510 kB) Collecting s3transfer==0.4.2 Downloading s3transfer-0.4.2-py2.py3-none-any.whl (79 kB) Collecting six==1.16.0 Downloading six-1.16.0-py2.py3-none-any.whl (11 kB) Collecting sqlparse==0.4.1 Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB) Collecting urllib3==1.26.4 Downloading urllib3-1.26.4-py2.py3-none-any.whl (153 kB) Collecting whitenoise==5.2.0 Downloading whitenoise-5.2.0-py2.py3-none-any.whl (19 kB) Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py): started Building wheel for psycopg2 (setup.py): finished with status 'done' Created wheel for psycopg2: filename=psycopg2-2.8.6-cp39-cp39-linux_x86_64.whl size=523851 sha256=21de473d6954ed53994462119b202ca6439f637a2cd8ccea561280b7101f3516 Stored in directory: /tmp/pip-ephem-wheel-cache-gid0o7zt/wheels/a2/07/10/a9a82e72d50feb8d646acde6a88000bbf2ca0f82e41aea438a Successfully built psycopg2 Installing collected packages: asgiref, jmespath, … -
DRF get_queryset check if in ManyToManyField
I have a model like this: class Project(models.Model): name = models.CharField("Name", max_length=8, unique=True) status = models.CharField( "Status", max_length=1, choices=[("O", "Open"), ("C", "Closed")], default="O", ) description = models.CharField("Description", max_length=3000, default="") owner = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name="project_owner" ) participants = models.ManyToManyField(User, related_name="project_participants", blank=True) created_at = models.DateTimeField(auto_now_add=True) Now in this model's ViewSet I have a get_queryset method: def get_queryset(self): if self.request.user.is_superuser: return Project.objects.all() else: return Project.objects.filter(owner=self.request.user.id) So when I get a project or projects, I only search for the projects that a user (hidden in the request, in JWT) owns. But now I thought about searching for the projects that user participates in (so the user appears in participants field list). How can I do that in get_queryset? -
How do I customize the Django "Password_reset_confirm" form?
I need to modify the labels and give a max_length to the django form for restoring password (The one after clicking on an email link to restore the password). I have done it for AuthenticationForm, UserCreationForm, UserChangeForm and PasswordChangeForm so far but i don't get to find a way to do it for the Password_reset_confirm Form. This example for the AuthenticationForm shows how I'm overriding all the forms. Forms.py from django.contrib.auth.forms import AuthenticationForm class loginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(), max_length=64) password = forms.CharField(widget=forms.PasswordInput(), max_length=64) class Meta: model = User fields = ( "username", "password" ) -
How to use a Django modelformset with extra fields?
Here is the example of an inline formset from Django's docs: from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=100) >>> from django.forms import inlineformset_factory >>> BookFormSet = inlineformset_factory(Author, Book, fields=('title',)) >>> author = Author.objects.get(name='Mike Royko') >>> formset = BookFormSet(instance=author) Suppose I want to let someone enter multiple book reviews at once, where each book review is for a particular book. (I'll have a query in my code to get the books to review.) How do I display a formset (model formset? inline formset?) of BookReview, but with some of the book data (e.g., title) on the form, so people know which book they are reviewing? So, the model is class BookReview(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) review_text = models.CharField(max_length=1000) Now how to initialize the formset? Below is some code, but based on my actual example (not book reviews), it's not going well. Sample code to initialize a formset (but incomplete): # pick some books to review # this could change, I don't want to couple it directly to the formset books_to_review = Book.objects.filter(author=an_author)[:3] class BookReviewForm(models.ModelForm): class Meta: model = BookReview fields = ('review_text') # How do I get Book.title (and possibly … -
Django EmalField form input is always set to active
so I have this form as on this image below. The point is that if the user clicks any of the fields, the text (which is essentialy a label, not a placeholder) rises up which shows that the clicked input field is active. However, I've tried to create a customized user creation in Django, which is just to have the email as the main user identificator, not the username. Now everything else works as supposed, but the thing is that the email field always appears as active (you know, the css attribute). I will now paste a scary amount of code and I will be happy if you could find out what's wrong. Sorry for the trouble `class UserManager(BaseUserManager): # handles user creation, havent' tested yet def create_user(self, email, username, password=None): # creates user with email as their id if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an username') if not password: raise ValueError('Users must have a password') user = self.model( email=self.normalize_email(email), password=password, username=username, ) user.set_password(password) user.save(user=self._db) return user class User(AbstractBaseUser): # user model, was just trying out some stuff username = models.CharField(verbose_name='username', max_length=30) email = models.EmailField(verbose_name='email', unique=True, max_length=60) date_joined = … -
In my PayPal server side integration, the payment popup immediately closes. How do I fix this?
I'm trying to setup paypal server side integration, but I keep stumbling on what is likely a very simple issue. The paypal payment browser window briefly appears to be loading, but it closes before I can do anything; it doesn't reach the login page or anything. In my django logs, I don't see any errors. Similarly, nothing stands out to me when I search the network activity. If I use a direct link to the paypal authorization page, I don't have any issues. Views.py def setUpAuthorization(request, max_price = 100): environment = SandboxEnvironment(client_id = settings.PAYPAL_CLIENT_ID , client_secret = settings.PAYPAL_CLIENT_SECRET) client = PayPalHttpClient(environment) # get_item request = OrdersCreateRequest() # Make initial authorization request.request_body( { "intent": "AUTHORIZE", "application_context": { "return_url": "https://www.example.com", "cancel_url": "https://www.examples.com", }, "purchase_units":[ { "description": "DESCRIPTION", "amount": { "currency_code": "USD", "value": max_price, }, } ]} ) response = client.execute(request) data = response.result.__dict__['_dict'] links = data['links'] for link in links: if link['rel'] == 'approve': paypal_link = link['href'] # redirect(paypal_link) return JsonResponse(data) html <div id="paypal-button-container"></div> <script src="https://www.paypal.com/sdk/js?client-id={{client_id}}"> </script> <script> var CSRF_TOKEN = '{{ csrf_token }}'; </script> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; …