Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React development server serves django backend, but django cannot receive pages from react on same server
So I am running a react django server based on a tutorial here: http://v1k45.com/blog/modern-django-part-1-setting-up-django-and-react/ My django server is running on port 80, which I have portforwarded, and my react development server is running port 3000. When I access my website on localhost(port 80), I am able to render the react default homepage. However, when I access the website externally, I am able to access the django server at port 80, but the react portion does not render, giving me a blank screen. Would be grateful to someone who could help me with this problem, just starting web development in django and react in general and it's giving me a lot of bumps. Thanks! -
how to get Boolean field from models in django
i have on model in django 1.8 class Tapp(models.Model): active = models.BooleanField(default=False) in django i need to use if else so i am doing like this if Tapp.objects.get('active',None): //if active value is true return Response("your alive", status=_status.HTTP_200_OK) else: return Response("your not alive", status=_status.HTTP_400_BAD_REQUEST) but i ma getting error like middleware.RequestResponseMiddleware.process_exception msg: Exception: ('too many values to unpack',); -
Pass url parameter to Django ModelForm without rendering it as input on form
I have a url /<subject_id>/comments/new/ which renders a Django ModelForm. I am using a view class derived from FormView to process the form. I wish to do the following: subject_id should not appear on the rendered form. subject_id should be added to the form prior to is_valid() being called, or if this is not possible should be added to the Comment instance. forms/comment_form.py: class CommentForm(ModelForm): class Meta: model = Comment fields = ['text'] views.py: class OrderCreate(FormView): form_class = CommentForm def form_valid(self, form): # Do some stuff to the validated Comment instance # Maybe save the comment, maybe not return super().form_valid(form) How do I do this? If I add subject_id as a field in CommentForm then it appears on the rendered form. If I don't then the form is instantiated with subject_id present from `self.kwargs['subject_id'] and complains of an "unexpected keyword argument". -
How can I receive JSON data from a API in same django project without using requests model?
I have a API defined in my project which returns JSON data in response. url(r'^api/report/(?P<report_id>\w+)/generate/', staff_member_required(api_views.GenerateReport.as_view()), name="generate_report"), In another app of same project, I want to receive this data in views.py How do I make a request to this url using some django functions. I think there might be some way to make this GET request without using requests or any other 3rd party module. Any help would be appreciated. -
Django Allauth Signup Prevent Login
Is there anyway to prevent the Allauth Signup form from automatically logging in the User? I found a similar post here with no answers: prevent user login after registration using django-allauth Thank you. -
pdf2image OSError on Django live code
I have a Django with nginx web application. I'm trying to convert a PDF to an image. The code works locally, but is giving me an OSError at /my_function/ [Errno 2] No such file or directory error when I push to my live server. # read existing PDF UNREDACTED_PDF = PdfFileReader(request_file.file) WIP_PDF = PdfFileWriter() # add page page = UNREDACTED_PDF.getPage(0) WIP_PDF.addPage(page) # convert to image and back pdf_buffer = io.BytesIO() WIP_PDF.write(pdf_buffer) PDFS_AS_IMAGES = StringIO() scanned_pages = pdf2image.convert_from_bytes(pdf_buffer.getvalue(), fmt="ppm") scanned_pages[0].save(PDFS_AS_IMAGES, "PDF",resolution=100.0) contents = PDFS_AS_IMAGES.getvalue() PDFS_AS_IMAGES.close() With Debug = True, I'm seeing the error in this line of my code: scanned_pages = pdf2image.convert_from_bytes(pdf_buffer.getvalue(), fmt="ppm") with the error statements going down: return convert_from_path(f.name, dpi=dpi, output_folder=output_folder, first_page=first_page, last_page=last_page, fmt=fmt, thread_count=thread_count, userpw=userpw) page_count = __page_count(pdf_path, userpw) proc = Popen(["pdfinfo", pdf_path], stdout=PIPE, stderr=PIPE) Raise child_exception OSError(2, 'No such file or directory') I understand this is a specific question. What is the thought process to go to to address something like this? -
django CharField encoding problems, converting \n to Â
My Django app is producing  characters in its form input. Other weird things happen, but the obvious repeatable one is &nbsp;\n (or maybe &nbsp;\n\r?) always converts to  This appears to be an unicode encoding bug in my app, which is getting confused somewhere between UTF-8 encoding and ISO-8859-1 My django app is using a postgresql database, and I've checked it's encoding: Encoding: UTF-8 Collate: en_CA.UTF8 Ctype: en_CA.UTF8 The webpage on which the form exists, has UTF-8: <!DOCTYPE html> <html lang="en"> <head> I don't see anywhere that django sets this, but I do have: LANGUAGE_CODE = 'en-us' Here's an one of the forms that exhibits the bad behaviour: class SubmissionReplyForm(forms.Form): comment_text = forms.CharField(label='Reply', widget=forms.Textarea(attrs={'rows': 2})) <meta charset="utf-8"> Here's the model and field where the bad behaviour is saved: class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) text = models.TextField() ... With my app's virtualenv activated: (venv) AgeOf@sparagus ~/myApp $ python Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.getdefaultencoding() 'utf-8' >>> Where else can I look for the source of this encoding error? Thanks! -
How to alter the LoginSerializer for one field for username/telephone/email?
In the custom LoginSerializer: class LoginSerializer(serializers.Serializer): username = serializers.CharField(required=False, allow_blank=True) email = serializers.EmailField(required=False, allow_blank=True) password = serializers.CharField(style={'input_type': 'password'}) def _validate_email(self, email, password): user = None if email and password: user = authenticate(email=email, password=password) else: msg = 'must input email and password' raise exceptions.ValidationError(msg) return user def _validate_username(self, username, password): user = None if username and password: user = authenticate(username=username, password=password) else: msg = 'must input username and password' raise exceptions.ValidationError(msg) return user def _validate_username_email(self, username, email, password): user = None if email and password: user = authenticate(email=email, password=password) elif username and password: user = authenticate(username=username, password=password) else: msg = 'must type in email and pwd or username and pwd' raise exceptions.ValidationError(msg) return user def validate(self, attrs): username = attrs.get('username') email = attrs.get('email') password = attrs.get('password') user = None if 'allauth' in settings.INSTALLED_APPS: from allauth.account import app_settings # Authentication through email if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.EMAIL: user = self._validate_email(email, password) # Authentication through username if app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.USERNAME: user = self._validate_username(username, password) # Authentication through either username or email else: user = self._validate_username_email(username, email, password) else: # Authentication without using allauth if email: try: username = User.objects.get(email__iexact=email).get_username() except User.DoesNotExist: pass if username: user = self._validate_username_email(username, '', password) # Did we get back … -
How to render a html page without view model?
Is it possible to render an HTML page without having a view model in Django if a page is going to display only static HTML? Basically, I want to delete an issue from a webpage and then show a 'successfully deleted' static HTML page after deleting. But I got blew error, anyone could help? NoReverseMatch at /project/1/issue/14/delete_issue/ Reverse for 'nice_delete.html' not found. 'nice_delete.html' is not a valid view function or pattern name. view.py def delete_issue(request,project_id,issue_id): if not request.user.is_staff or not request.user.is_superuser: raise Http404 issue = get_object_or_404(Issue,id=issue_id) issue.delete() return redirect(reverse('project:issue_tracker:nice_delete.html')) urls.py urlpatterns =[ path('',views.list_of_issue,name='list_of_issue'), path('<int:issue_id>/',views.issue_detail,name='issue_detail'), path('<int:issue_id>/comment',views.add_comment,name='add_comment'), path('new_issue/',views.new_issue,name='new_issue'), path('<int:issue_id>/edit_issue/',views.edit_issue,name='edit_issue'), path('<int:issue_id>/delete_issue/',views.delete_issue,name='delete_issue'), ] nice_delete.html {% extends 'base.html' %} {% block content %} <p>Successfully delete this issue</p> {% endblock %} -
How to connect Dialogflow with Django?
I have this project where I have to make a bot for a internal platform and for some answers I need to use my data base, I havee been taking a look at Dialogflow's API but it's not clear to me. I just need some guidance and tips to achieve this. I have been taking a look at some tutorials with node.js but it's different and I can't find an answer because it isn't a common integration for Dialogflow. -
Django: how to get other objects of a class
I am not able to get the object population and languages. class countries(models.Model): country_name = models.CharField(max_length=200,null=True) population = models.IntegerField(verbose_name = "Population") languages = models.CharField(max_length=200,null=True) def __str__(self): return self.country_name By using the models.ForeignKey, I am able to access country_name but not the population and languages of that country class pop(models.Model): c_pop = models.ForeignKey(countries,on_delete=models.CASCADE) accessed = models.CharField(max_length=200,null=True) def __str__(self): return self.accessed Is there any way I can access all the objects of class countries just by choosing the country_name from class pop. Thank you -
Django Full-Text Search with multiple words
This isn't really a compplex problem (to my knowledge). I know in MongoDB you can feed in a string and it automatically tokenizes and performs full-text search using that string as a query. However, in Django, I have yet to find similar functionality, and all of the examples I've seen have done something along the lines of: from django.contrib.postgres.search import SearchQuery query = SearchQuery('foo') Is the reason people only use one word because SearchQuery can only use one word? What I want to know is how to perform full-text search with multiple words. Is it as easy as doing from django.contrib.postgres.search import SearchQuery query = SearchQuery('foo and also bar') ? Or does it need to be more complicated than that? -
How to start a long-running thread in Python/Django
I have a code which monitor cart,based on the user setting "how_often"(options are every 1,3 or 7 day).And I schedule it via schedule def startScheduleThread(how_often_setting, cart_id): if how_often_setting==7: schedule.every().monday.do(monitor_cart, cart_id) elif how_often_setting==3: schedule.every(3).days.at("10:30").do(monitor_cart, cart_id) elif how_often_setting==1: schedule.every(1).day.do(monitor_cart, cart_id) else: pass while True: schedule.run_pending() time.sleep(3600) it's a long-running task, i decided to start a new thread(so main thread ain't blocked) how_often_setting = cart.how_often cart_id=cart.pk thread_obj = threading.Thread(target=startScheduleThread, args=[how_often_setting, cart_id]) thread_obj.start() the point is it works perfectly fine on a development server, but once i upload in on a real server - it does nothing. Can anyone tell me why it's usually happening and how to even start such a long-running task. Thank you in advance P.S. Please don't suggest Celery -
Django template using Bootstrap-Table with Pandas DF
Inheriting from this question which wasn't completed to a workable code solution from what I can tell. I'm trying to get a very simple wenzhixin/bootstrap-table to work. I can print the columns and data objects to the console - so they work. Here are the code snippets: #variables qs = a django queryset df = a pandas dataframe #views.py class MyView(generic.ListView): # some stuff to get qs = queryset df = read_frame(qs) json = df.to_json() columns = [{'field':f, 'title': f} for f in MyModel._meta.fields] context = { 'columns': columns, 'data': json,} return context #MyView.html <script src='/path/to/bootstrap-table.js'> <script src='/path/to/pandas_bootstrap_table.js'> <script src='/path/to/bootstrap-table.css'> <script src='/path/to/pandas_bootstrap_table.js'> <script src='/path/to/bootstrap.min.cs <script src='/path/to/jquery-3.3.1.slim.min.js <script src='/path/to/popper.min.js <script src='/path/to/bootstrap.min.js <script src='/path/to/jquery.min.js <table id='datatable'></table> There are other elements in the view using bootstrap - everything else works - just the last line where it has a table with id='datatable' isn't rendering. The pandas_bootstrap_table.js is where I've spent my most time trying to get the function to call. I believe this is where the problem is. #pandas_bootstrap_table.js $(function() { $('#datatable').bootstrapTable({ striped: true, pagination: true, showColumns: true, showToggle: true, showExport: true, sortable: true, paginationVAlign: 'both', pageSize: 25, pageList: [10, 25, 50, 100, 'ALL'], columns: {{ columns|safe }}, data: {{ data|safe }}, }); … -
Password not being hashed
I created a registration form and two custom user types; students and parents. The registration works perfect for both users. The problem is when I go to django admin and view my users, the password for students is in a hashed algorithim, while for parent users the password field says "Invalid password format or unknown hashing algorithm". I'm unsure where the problem stems from, but assume it is from my parent form inheriting the register form. Any help will be appreciated, thanks! models.py class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) child_first_name = models.CharField(max_length=255) timestamp = models.DateTimeField(auto_now_add=True) student = models.BooleanField(default=False) parent = models.BooleanField(default=False) teacher = models.BooleanField(default=False) active = models.BooleanField(default=True) # can login staff = models.BooleanField(default=False) # staff user, not superuser admin = models.BooleanField(default=False) # superuser objects = UserManager() # takes email as username | removes email USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email def has_perm(self, perm, onj=None): "Does the user have a specific permission?" return True def has_module_perms(self, app_label): "Does the user have permissions to view the app 'app_label'?" return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active class ParentProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) … -
How to get data and put it into edit form Django
I used Django to create a blog like web page and I would like it to have 'edit' function.I created an edit page for my blog(issues), but I could not put data into my edit form(edit_issue), anyone please help? view.py def edit_issue(request, project_id,issue_id): issue = get_object_or_404(Issue, id=issue_id) if request.method == 'POST': form = NewIssueForm(request.POST,instance=issue) if form.is_valid(): issue = form.save(commit=False) issue.author = request.user issue.save() return redirect('project:issue_tracker:issue_detail',project_id=project_id,issue_id=issue_id) else: form = NewIssueForm() template = 'issue_tracker/issue/edit_issue.html' context = {'form': form} return render(request, template, context) urls.py from django.conf.urls import url from django.urls import path from . import views app_name = 'issue_tracker' urlpatterns =[ path('',views.list_of_issue,name='list_of_issue'), path('<int:issue_id>/',views.issue_detail,name='issue_detail'), path('<int:issue_id>/comment',views.add_comment,name='add_comment'), path('new_issue/',views.new_issue,name='new_issue'), path('<int:issue_id>/edit_issue/',views.edit_issue,name='edit_issue'), ] forms.py class NewIssueForm(forms.ModelForm): class Meta: model = Issue fields = ('title','content','project','status') edit_issue.py {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h1>Issue Update</h1> <form method="POST" class="Issue-form">{% csrf_token %} {{form|crispy}} <button type="submit" class="btn btn-success">Submit</button> </form> {% endblock %} -
Django-ModelTranslation not working on Safari
I'm using Django-ModelTranslation 0.12.2 to provide translation fields for a site using Mezzanine 4.2.3 and Django-Oscar 1.5.2. It's Django 1.10.8 under the hood. I have two languages: English and Russian. Things work well on Chrome and Edge. Press either the English or Russian selectors and the desired language loads. But it doesn't work on Safari. As far as I know, these are the lines involved: settings.py: USE_MODELTRANSLATION = True MODELTRANSLATION_FALLBACK_LANGUAGES = ('en',) LANGUAGE_CODE = "en" LANGUAGES = ( ('en', _('English')), ('ru', _('Russian')), ) language_selector.html: {% load i18n %} {% get_language_info_list for LANGUAGES as languages %} {% if settings.USE_MODELTRANSLATION and languages|length > 1 %} {# hide submit button if browser has javascript support and can react to onchange event #} <script> function myFunction() { document.getElementById("language_selector_form").submit(); } </script> <form action="{% url "set_language" %}" method="post" id="language_selector_form"> {% csrf_token %} <div class="form-group"> <div class="btn-group btn-group-sm" role="group" aria-label="..."> {% for language in languages %} <button name="language" type="submit" class="btn btn-secondary" value="{{ language.code }}" onclick="myFunction()">{{ language.code }}</button> {% endfor %} </div> </div> </form> </div> {% endif %} I suspect document.getElementById("language_selector_form").submit(); might be the problem because the Safari console shows this error: MutationObserver is not supported by your browser plugins.js:1319 WOW.js cannot detect dom mutations, please call .sync() … -
Login form doesn't work with multiple user types
In my application I have two custom user profiles. They are student and parent. The registration for both user types work great and they are stored in the database. The login form works as well. The problem is the login form only authenticates and logs in student accounts, not parent types. I'm unsure where the problem stems from. I appreciate any help I can get, thank you! models.py class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) child_first_name = models.CharField(max_length=255) timestamp = models.DateTimeField(auto_now_add=True) student = models.BooleanField(default=False) parent = models.BooleanField(default=False) teacher = models.BooleanField(default=False) active = models.BooleanField(default=True) # can login staff = models.BooleanField(default=False) # staff user, not superuser admin = models.BooleanField(default=False) # superuser objects = UserManager() # takes email as username | removes email USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email def has_perm(self, perm, onj=None): "Does the user have a specific permission?" return True def has_module_perms(self, app_label): "Does the user have permissions to view the app 'app_label'?" return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active class ParentProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) child_first_name = models.CharField(max_length=255) timestamp = … -
Django MPTT product list filter by category
I have two models in Django - Product and Category - and I want to be able to filter through my products by category in the Django admin panel; however, I want the filters to be recursive, so if I have nested categories, clicking on a parent category will also show all of the products that are in the child categories. Here's my model code so far: class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) category = models.ForeignKey('Category', on_delete=models.PROTECT) date_added = models.DateField(auto_now_add=True) last_modified = models.DateField(auto_now=True) def __str__(self): return self.name class Category(MPTTModel): parent = TreeForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='children') name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class MPTTMeta: order_insertion_by = ['name'] parent_attr = 'parent' And this is my admin code so far: class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'price', 'category', 'date_added', 'last_modified') list_filter = ('date_added', 'last_modified', ('category', TreeRelatedFieldListFilter)) class CategoryAdmin(admin.ModelAdmin): list_display = ('name', 'parent') admin.site.register(Product, ProductAdmin) admin.site.register(Category, MPTTModelAdmin) I tried creating the following list filter class to use in the product list_filter (as well as several other, similar methods), but no matter how I set this up I keep getting errors along the lines of object has no attribute get_descendents: class ProdCategoryListFilter(admin.SimpleListFilter): title = _('category') parameter_name = 'category' def lookups(self, … -
How To Deploy Django 2.0.6 Python 3 App?
Finally I finished my first Django application now I am looking to deploy the website online so everyone can access; I tried Web-min which is a free server control panel, they have an old version of Django but no success, I also have an account with Goddady c panel but they don't support Python and Django. I want to know how I can make this last step to deploy my web application please advise. -
The `length` and `name` sort params do not meet my requirement
I have a PhysicalServer model: class PhysicalServer(models.Model): name = models.CharField(max_length=32) cabinet = models.ForeignKey(to=Cabinet, on_delete=models.DO_NOTHING, related_name="physical_servers") physical_server_model = models.ForeignKey(to=PhysicalServerModel, null=True, on_delete=models.DO_NOTHING) ... class Meta: ordering = ['-cabinet', '-physical_server_model', 'name'] its list API view is this: class PhysicalServerListAPIView(ListAPIView): serializer_class = PhysicalServerListSerializer permission_classes = [AllowAny] pagination_class = CommonPagination def get_queryset(self): qs = PhysicalServer.objects.filter(**filters) return qs.annotate(length=Length('name')).order_by('length', 'name') # there if I put the `name` first(order_by('name', 'length')), also inconformity my requirement. my physicalserver instance name like this bellow: My question is, when I use this for list sort: return qs.annotate(length=Length('name')).order_by('length', 'name') the result will be: SE01-A1 SE01-A2 SE01-A3 ... SE01-A9 SE01-C1 SE01-C2 SE01-C3 ... SE01-A10 SE01-A11 SE01-A12 ... if I use the bellow for sort: return qs.annotate(length=Length('name')).order_by('name', 'length') the result will be: SE01-A1 SE01-A11 SE01-A12 SE01-A13 ... SE01-A2 SE01-A21 ... SE01-A3 ... How can I sort like this: SE01-A1 SE01-A2 SE01-A3 SE01-A4 ... SE01-A10 ... SE01-C1 SE01-C2 ... -
Admin Django fieldset creating new user creation form
I have two diffeent fieldsets depending on wether a user is in the 'leader' group or not. The fieldset show exactly what I want, except when I try to add a new user, from a user in the 'Leader' group, I now get a different user creation form. I got how to do the different fieldsets from here, and I tried ensuring the form is indeed the right one by overriding the custom form as done here. class UserCreateForm(UserCreationForm): class Meta: model = User fields = ('username', 'password1', 'password2') class UserProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'UserProfile' fk_name = 'scout_username' class CustomUserAdmin(UserAdmin): #ensuring it's the right form add_form = UserCreateForm add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username', 'password1', 'password2'), }), ) inlines = (UserProfileInline, ) fieldsets = ( ((None), {'fields': ('username', 'password')}), (('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), (('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (('Important dates'), {'fields': ('last_login', 'date_joined')}), ) leader_fieldsets = ( ((None), {'fields': ('username', 'password')}), (('Personal'), {'fields': ('first_name', 'last_name')}), ) #making it so leaders can only view the fields within leaders_fieldset #removing this also removes the problem yet all the fields are shown regardless of the user's group def get_fieldsets(self, request, obj=None): … -
Django 2.X Model - Get aggregated data as time intervals
I have the following tasks: Get all SUM of an attribute grouped by a time interval of 5 Minutes. I know how to do it in (My)SQL, but not with the Django Model ORM System. The following MySQL Query works fine: SELECT DATE_FORMAT( MIN(createdAt), '%d/%m/%Y %H:%i:00' ) as adjusted_date,SUM(number_of_items), COUNT(id) FROM app_model GROUP BY ROUND(UNIX_TIMESTAMP(app_model.createdAt) DIV 300); I have the following Django Code so far: MyModel.objects.filter(my_attribute=my_value).order_by( "mymodel.createdAt").extra({'minute': 'minute(mymodel.createdAt)'}).values("minute").annotate( TotalAmount=models.Sum("number_of_items")) The SQL Returns the following result: The problem with the Django result is, that it is taking every minute. Which means, that if there are 5 rows within the same minute, it will return 5 times that row. Furthermore, there is no "real 5 minute"-interval. I am using MySQL, Python 3.6.5 and Django 2.0.6 As an example, this is the model: class BaseModel(models.Model): uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False, verbose_name='UUID') number_of_items = models.DecimalField(default=0, decimal_places=10, max_digits=16) createdAt = models.DateTimeField(auto_now_add=True, auto_now=False, editable=False, verbose_name=_('created')) updatedAt = models.DateTimeField(auto_now=True, editable=False, verbose_name=_('updated')) -
How do you handle conditional html formating?
In one of my html pages I have the following: {% for bet in recent_bets %} {% if bet.status__name == "Won" or bet.status__name == "Half Won"%} <div class="container col recent-form_col bg-success" data-toggle="tooltip" data-placement="top" title="{{ bet.date }}, {{ bet.time }}"> {% elif bet.status__name == "Lost" or bet.status__name == "Half Lost"%} <div class="container col recent-form_col bg-danger" data-toggle="tooltip" data-placement="top" title="{{ bet.status }}"> {% elif bet.status__name == "Void" or bet.status__name == "Cancelled"%} <div class="container col recent-form_col bg-secondary" data-toggle="tooltip" data-placement="top" title="{{ bet.status }}"> {% elif bet.status__name == "Cash Out" %} <div class="container col recent-form_col bg-warning" data-toggle="tooltip" data-placement="top" title="{{ bet.status }}"> {% endif %} Based on what the bet.status__name is, it returns a different background color ex bg-success. Apart from this case, I have a few other cases similar to that. I would like to know how do you handle these things. Just leave it in the html, create a filter/tag that returns the appropriate html or something else ? -
Django stripe connect account creation
I am trying to create an account on stripe connect, using the code provided by stripe. Everything is working fine, I submit the create and I record the stripe_id to my database, however if I want to get the keys alos how can I retrieve them, what is the proper syntax to do so? here is my code in the view: if form.is_valid(): mail = form.cleaned_data['email'] name = form.cleaned_data['first_name'] lastName = form.cleaned_data['last_name'] country = form.cleaned_data['country'] stripeId = stripe.Account.create(type="custom", country=country, email=mail, ) p = UserStripe.objects.create( user=request.user, stripe_id=stripeId['id']) print(p) print(stripeId['id']) the keys are retured by the api as: <Account account id=... at 0x00000a> JSON: { "id": "acct_1033zf2gFw4ArzaQ", . . . "keys": { "secret": "sk_test_AdveEkmolYxHOzV4K4qLWoJt", "publishable": "pk_test_Gt3Bk3C07gz2wnrI3hQWJQIi" } } so to get the id I am using stripeId['id'], but how can I get the info inside the keys and pass it to my database? Thank you