Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django sort filtered objects by other model's value
i have following models and i filtered all Songs by Item's object_id field. But then i need to use Item's position to sort them. Is there any way to filter Songs and filter it by `Items' position? class Chart(models.Model): title = models.CharField(max_length=120) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=CONTENT_TYPE_LIMIT) class Version(models.Model): chart = models.ForeignKey("Chart", related_name="versions", on_delete=models.CASCADE) class Item(models.Model): edition = models.ForeignKey(Version, on_delete=models.CASCADE, related_name="items") object_id = models.UUIDField(db_index=True) position = models.PositiveIntegerField() Now i get the chart first by list_ids = chart.versions.last().items.all() and to get Songs i run Songs.objects.filter(id__in=list_ids) But i need to do order_by('position') for this too. Maybe my approach of getting all Songs was wrong. Because Items's object_id must be a Songs id though it is intentionaly not a ForeignKey though. -
In Django REST Framework, how to access kwargs context in html template? {{ view.kwargs.foo }} doesn't work for me
Referring this answer I couldn't access the kwargs in the html template by {{ view.kwargs.foo }}. Not sure why, is it because something's different with DRF so I need a different syntax to access it? My html template ('polls/character_description_list.html'): {% block content %} <table> {% for description in descriptions %} <tr> <td><b>{{ description.title }}</b></td> <td>{{ description.content }}</td> </tr> {% endfor %} </table> <form action="{% url 'polls:description_detail_create_from_character' %}"> <input type="hidden" value="{{ view.kwargs.character_id }}" name="character_id"> <!-- This is where I attempt to access the kwargs but can't get it, although I can attempt to output it anywhere else for debugging --> <input type="submit" value="New Description"/> </form> {% endblock %} Therefore when submitting I expect to go to: http://localhost:8000/myapp/description_detail_create_from_character/?character_id=1 But in reality the id is missing: http://localhost:8000/myapp/description_detail_create_from_character/?character_id= To check if the character_id token I am looking for is in kwargs, I did try to breakpoint (using PyCharm) in get_serializer_context: def get_serializer_context(self): context = super(CharacterDescriptionListView, self).get_serializer_context() return context Examined the context, I can find 'view' -> kwargs -> 'character_id', with the value I am expecting, so it should work. This is my views.py: class CharacterDescriptionListView(DescriptionViewMixin, CustomNovelListCreateView): template_name = 'polls/character_description_list.html' def get_filter_object(self): return get_object_or_404(Character, id=self.kwargs['character_id']) def get_queryset(self): characterObj = self.get_filter_object() return Description.objects.filter(character=characterObj) -
Mock a Django Model method
I am trying to mock a method in a different file, but am unsure of what I am doing wrong. #a.py @patch("b.Trigger.is_valid_trigger") def true(*args,**kwargs): return True class TriggerTest(AsyncTestCase): async def test_apply_working(self): await b.Trigger().is_valid_trigger() #b.py class Trigger(Module): async def is_valid_trigger(self, event): raise NotImplementedError() However, still a NotImplementedError is raised. Any help is appreciated. -
django cms plugin - editing related object automatically publish changes
On editing related object used via TabularInline changes for that automatically publish on page. While editing related object request goes through admin page. On live editing page, when changed is made in cms plugin for related object, request goes through admin page. Than changes for that related objects are automatically published on page without need to use button for publish changes on site. Also same situation happens when related object is saved via admin page. models: from cms.models.pluginmodel import CMSPlugin from django.db import models from django.utils.translation import ugettext_lazy as __ from djangocms_text_ckeditor.fields import HTMLField from filer.fields.image import FilerImageField from plugins.generic.cards.styles import ( CARD_OPTIONS, HOVER, MARGIN_SIZES, CARD_SECTION_OPTIONS, HEADER_SECTION_OPTIONS ) from plugins.generic.global_choices import ( BUTTON_COLOR, LINK_TARGET, BACKGROUND_COLOR, BORDER_COLOR, LINK_COLOR, ) from .utils import ChoiceArrayField, GridSystem class Card(models.Model): """Generic card model that is compatible with the Bootstrap grid system.""" name = models.CharField(max_length=100) size = models.ForeignKey( GridSystem, verbose_name=__('Card size'), help_text=__( 'Specify card size for different resolutions using ' 'grid system from Bootstrap.' ), ) background = models.CharField( verbose_name=__('Card background color'), max_length=100, choices=BACKGROUND_COLOR, blank=True, null=True, help_text=__('Transparent by default.'), ) hover = models.CharField( verbose_name=__('Card hover effect'), max_length=100, choices=HOVER, blank=True, null=True, help_text=__( 'Choose what should happen when card is pointed with a cursor.' ), ) options = … -
How to create Django queryset filter to compare Specific value of two different tables in django?
i have created two different model name employeeProfile and Jobs.Both table contains same charfield 'title'. here i want to compare/match both title and return the 'title' of JOb model. -
how to load an document from my pc into website using django
I m using Django framework and i need to create a button like " From here download your pdf ", and when i click it, to download a specific document from my pc. I need also the code from View and html part if you can -
react frontend for django without any rest api calls
At the moment I have a django backend with jquery frontend. Looking to move to reactjs. The issue is that I don't have a server per se, so I can't make calls to django from frontend. My website is not publicly available, but sent as a html document by email. So django is used just to crunch a lot of data and make a lot of plots and tables, then I use django-bakery to output all of that into a static html file that gets sent by email. My question is how would you go from a standard django html template: <div class="card"> {% for k, v in tables.items %} <div id="{{ k }}"> To a reactjs template, without making calls to a django server. How would I get the data from django? Thanks! -
Efficient way of updating real time location using django-channels/websocket
I am working on Real Time based app, it needs to update location of user whenever it is changed. Android app is used as frontend, which get location using Google/Fused Api and in onLocationChanged(loc:Location), I am sending the latest location over the Websocket. The location update is then received by a django channel consumer, and job of this consumer is to store location in database asynchronously (I am using @database_sync_to_async decorator. But the problem is, server crashes when Android app tries to send 10-15 location updates per second. What will be the efficient way of updating real time location? Note: Code can be supplied on demand -
Django: Problem with filtering products in order
I'm trying to make account view in my django-shop. I want to display information about the order and the ordered goods. I have a ProductInOrder model with foreign key to Order. Now I want to filter the ordered goods by order. But something is going wrong. class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=15) items = models.ForeignKey(Cart, null=True ,on_delete=models.CASCADE, verbose_name='Cart') total = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, blank=True) phone = models.CharField(max_length=20) buying_type = models.CharField(max_length=40, choices=BUYING_TYPE_CHOICES, default='Доставка') address = models.CharField(max_length=250, blank=True) date_created = models.DateTimeField(default=timezone.now) date_delivery = models.DateTimeField(default=one_day_hence) comments = models.TextField(blank=True) status = models.CharField(max_length=100, choices=ORDER_STATUS_CHOICES, default='Принят в обработку') class ProductInOrder(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) item_cost = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) all_items_cost = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) And views.py def account_view(request): order = Order.objects.filter(user=request.user).order_by('-id') products_in_order = ProductInOrder.objects.filter(order__in=order) categories = Category.objects.all() instance = get_object_or_404(Profile, user=request.user) if request.method == 'POST': image_profile = ProfileImage(request.POST, request.FILES, instance=instance) if image_profile.is_valid(): avatar = image_profile.save(commit=False) avatar.user = request.user avatar.save() messages.success(request, f'Ваш аватар был успешно обновлен!') return redirect('ecomapp:account') else: image_profile = ProfileImage() context = { 'image_profile': image_profile, 'order': order, 'products_in_order': products_in_order, 'categories': categories, 'instance': instance, } return render(request, 'ecomapp/account.html', context) This line products_in_order = ProductInOrder.objects.filter(order__in=order) doesn't work. Any help please. -
How to send report mail like Google
I have a web using Django framework run in localhost, I want web send email automatically to a email address, but I have a trouble in config EMAIL_HOST, EMAIL_HOST_USER, EMAIL_HOST_PASSWORD and EMAIL_PORT in settings.py this is settings.py I configured: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_HOST = 'localhost' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 25 How can I fix to send email? -
Is there a way to call two function-based views from views.py from one url? - Django or even by using Class-based view
I have tried two different style of views: Function-based and class-based. I have two functions in my views.py and i don't know how to call both of them under single same url. I have seen suggestions to combine both functions into one but it still doesn't work. Tried get() from class-based view and called the same url with different views path('home/dashboard/', views.get_profile, name='dashboard'), path('home/dashboard/', views.get_dept, name='dashboard'), def get_dept(request, *args, **kwargs): dataset = Department.objects.all() \ .values('department') \ .annotate(IT_count=Count('department', filter=Q(department="IT")), Sales_count=Count('department', filter=Q(department="Sales")), Admin_count=Count('department', filter=Q(department="Admin")), HR_count=Count('department', filter=Q(department="HR"))) \ .order_by('department') categories = list() IT_series_data = list() Sales_series_data = list() Admin_series_data = list() HR_series_data = list() for entry in dataset: categories.append('%s Department' % entry['department']) IT_series_data.append(entry['IT_count']) Sales_series_data.append(entry['Sales_count']) Admin_series_data.append(entry['Admin_count']) HR_series_data.append(entry['HR_count']) IT_series = { 'name': 'IT', 'data': IT_series_data, 'color': 'green' } Sales_series = { 'name': 'Sales', 'data': Sales_series_data, 'color': 'yellow' } Admin_series = { 'name': 'Admin', 'data': Admin_series_data, 'color': 'red' } HR_series = { 'name': 'HR', 'data': HR_series_data, 'color': 'blue' } chart2 = { 'chart': { 'type': 'column', 'backgroundColor': '#E3F0E6', 'option3d': { 'enabled': "true", 'alpha': 10, 'beta': 15, 'depth': 50, } }, 'title': {'text': 'Containers per department'}, 'xAxis': {'categories': categories}, 'yAxis': { 'title': { 'text': 'No.of containers'}, 'tickInterval': 1 }, 'plotOptions': { 'column': { 'pointPadding': 0.2, 'borderWidth': 0, … -
usage of self.client.get() vs self.browser.get()
I'm working through this book about TDD with Django. I get different behaviour from using self.client.get('/') and different one from using self.browser.get('/localhost:8000') seemingly they look the same but getting different behaviour. Can anybody explain what's happening here ? -
Storing passwords in MySQL database in hashed form Django App
I am working on a Django app and my django is using MySQL database which can be handled through django admin page (inbuilt). Currently, I m creating users who can access the app by manually creating username and password in Django administration --> Authentication and Authorization --> users --> add. (that's what i want and hence my requirement is satidfied here.) When i create user and add password through django admin, it gets hashed and no one can see the password in plain text. Also, my django app consists of login through which user can authenticate and also it consists of model (Login) which records who has logged-in. But the problem here is that, when the user Logs-In the Login model stores the password in Plain text in Db (MySQL) and i want that the Login model should store the password in hashed form. Note:- i have included ALL the hashers in settings.py here's the code Models.py from django.db import models from datetime import datetime from django.contrib.auth.models import User # Create your models here. class LoginEvent(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date_and_time = models.DateField(auto_now_add=True) def __str__(self): return str(self.user) + ': ' + str(self.date) class Login(models.Model): #model that stores username and Password … -
How to blend elements with particle js backround?
Assuming i have a body tag that uses particle js. For every element i create, how do i blend background with body background? Rather than have an element that is just white, how can i make text that particle js can go behind? I tried Opacity but that just makes the body transparent without showing the background. html code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>particles.js</title> <link rel="stylesheet" media="screen" href="css/style.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body id="particles-js"> <div class="navbarAll"> <div class="navbar"> <div class="navbarButtons"> <button id="buttons" type="button" class="btn btn-outline-primary">Button</button> <button id="buttons" type="button" class="btn btn-outline-primary">Butotn</button> <button id="buttons" type="button" class="btn btn-outline-primary">Button</button> <button id="buttons" type="button" class="btn btn-outline-primary">Button</button> <a id="nameMy">TEXT</a> </div> </div> </div> <div class="mainContent"> <a>Hey</a> </div> <script src="../particles.js"></script> <script src="js/app.js"></script> </body> </html> CSS file (includes particle Js code: html,body,div,span,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,abbr,address,cite,code,del,dfn,em,img,ins,kbd,q,samp,small,strong,sub,sup,var,b,i,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,figcaption,figure,footer,header,hgroup,menu,nav,section,summary,time,mark,audio,video{margin:0;padding:0;border:0;outline:0;font-size:100%;vertical-align:baseline;background:transparent} body{line-height:1} article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block} nav ul{list-style:none} blockquote,q{quotes:none} blockquote:before,blockquote:after,q:before,q:after{content:none} a{margin:0;padding:0;font-size:100%;vertical-align:baseline;background:transparent;text-decoration:none} mark{background-color:#001;color:#FFFFFF;font-style:italic;font-weight:bold} del{text-decoration:line-through} abbr[title],dfn[title]{border-bottom:1px dotted;cursor:help} table{border-collapse:collapse;border-spacing:0} hr{display:block;height:1px;border:0;border-top:1px solid #ccc;margin:1em 0;padding:0} input,select{vertical-align:middle} li{list-style:none} html,body{ width:100%; height:100%; background:#FFFFFF; } html{ -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } body{ font:normal 75% Arial, Helvetica, sans-serif; } canvas{ display:block; vertical-align:bottom; } /* ---- stats.js ---- */ .count-particles{ background: #000000; position: absolute; top: 48px; left: 0; width: 80px; color: #000000; font-size: .8em; text-align: left; text-indent: 4px; line-height: 14px; padding-bottom: 2px; font-family: Helvetica, Arial, sans-serif; … -
Python requests put request to shopify api always gives error
I am calling shopify api to image upload in shopify theme through python requests library. I am using put request but it always gives me error like :{'error': "822: unexpected token at 'asset=key&asset=attachment'"} for any put request. Here is my headers:- endpoint_api_image = "https://{0}/admin/themes/{1}/assets.json".format(shop,theme_id) headers = { # 'Accept': 'application/json', "X-Shopify-Access-Token": token, "Content-Type": "application/json; charset=utf-8", } Here is my request to api:- data={ "asset": { "key": image_name, "attachment": encoded_image } } image_url =requests.put(endpoint_api_image,headers=headers, data=data) print(image_url.json()) The response i am getting: {'error': "822: unexpected token at 'asset=key&asset=attachment'"}. Where i am missing the point? It is happening for any put requests.Any help will be much appreciated. -
Django Improved UpdateView?
I have this UpDateView class and I need just author of article can edit the blog I had the solution for creating class and using def Form_valid but it doest work for UpdateView class ::: class ArticleUpdateView(LoginRequiredMixin,UpdateView): model = models.Article template_name = 'article_edit.html' fields = ['title','body'] login_url = 'login' class ArticleCreateView(LoginRequiredMixin,CreateView): model = models.Article template_name = 'article_new.html' fields = ['title','body',] login_url='login' def form_valid(self,form): form.instance.author = self.request.user return super().form_valid(form) -
LinkedIn Auth 2.0 in Django raises an error - how to catch errors
I am using social-auth-app-django to use the LinkedIn auth but it goes to the error process when I checked linked.py. In settings.py SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_emailaddress'] SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['emailAddress', 'profilePicture'] SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [ ('id', 'id'), ('firstName', 'first_name'), ('lastName', 'last_name'), ('emailAddress', 'email_address'), ('profilePicture', 'profile_picture') ] It stores the extra data in the 'social_auth_usersocialauth' table but it goes to process_error in linkedin.py in social_core and passes the data and returns the following data. def process_error(self, data): super(LinkedinOAuth2, self).process_error(data) print(data) if data.get('serviceErrorCode'): ... <QueryDict: {'code': ['xxx_code_value_xxx'], 'state': ['---state---']}> {'access_token': '---token--', 'expires_in': 5555555} It seems there are no error codes. What's wrong here? -
Dynamically filtering with __icontains from input field
I want to filter my fields in a model dynamically from a form input. Already searched a lot but did not find something suitable. As i am fairly new to django and all this stuff i might not see some obvious stuff. The form defines the field to search in and what to search(filter). This should lead to a url like http://localhost:8000/app/search/?col=id&q=1234 In my view i would like to modify the get_queryset() function with a filter like this: def get_queryset(self): query1 = self.request.GET.get('q') query2 = self.request.GET.get('col') object_list = mymodel.objects.filter( Q(query2__icontains = query1) ) Is this possible? Moe -
i want to convert the file(csv,excel,txt) as table in database dynamically
i want to convert the file(csv,excel,) as table in database dynamically and it should take the values from file and convert it as datatype and store it in sq-lite database. "i tried to convert using excel file." "output should save in sq-lite database" def upload(request): if request.method == "POST": form = fr_upload_file.UploadFileForm(request.POST, request.FILES) if form.is_valid(): filehandle = request.FILES['file'] d_excel=excel.make_response(filehandle.get_sheet(), "csv",) file_name=str(filehandle)) print("d_excel",d_excel) return d_excel -
Got Stuck when trying to deploy Sentimental Analysis model using Django
I am working to deploy a sentimental analysis model using django.I have created a simple form in which I am giving option to upload a csv file.Now how can I write a view for it without using models.My purpose is to upload the file then fetching the file from the user.Then reading the csv file as as dataframe.Then doing necessary predictions using the saved pickled models.Please provide after fetching the file from the user.How can I read it as as dataframe using pandas. Thank you very much -
django import-export, export multiple many to many models
I have Rule Model which has multiple RuleCondtion and RuleAction. I want to export these into a csv file. I am using django import-export for this. Example: name, priority, tags, conditions, actions Rule 1, 1000, "tag1,tag2", "[{"identifier":"A", "operator":"B"..}]", "[{"identifier":"A", "operator":"B"..}]" My Models: class Rule(models.Model): name = models.CharField(max_length=128, help_text="Name of Rule") description = models.TextField(help_text="Brief Description of Rule", blank=True) priority = models.IntegerField(default=1000, help_text="Priority of rule, lesser applies first") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) tags = models.ManyToManyField('Tag', blank=True) disabled = models.BooleanField(default=True) def __str__(self): return self.name class RuleCondition(models.Model): identifier = models.CharField(max_length=128, help_text="Select a Property", blank=True) operator = models.CharField(max_length=128, help_text="Select an Operator", blank=True, choices=CONDITION_OPERATOR_CHOICES) value = models.TextField(help_text="Content to match the rule") rule = models.ForeignKey('Rule', on_delete=models.CASCADE, related_name='conditions') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return 'Rule Condition ' + str(self.id) class RuleAction(models.Model): identifier = models.CharField(max_length=128, help_text="Select a Property", blank=True) operator = models.CharField(max_length=128, help_text="Select an Operator", blank=True, choices=ACTION_OPERATOR_CHOICES) value = models.TextField(help_text="Content to apply on the rule") rule = models.ForeignKey('Rule', on_delete=models.CASCADE, related_name='actions') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return 'Rule Action ' + str(self.id) How can I achieve this, there is no option in the django import-export to do this. -
Can't load two Highcharts on my Django web app
I'm currently using Highcharts with Django. Not too sure it's either an error in implementation at the django views.py or the Highcharts code itself. Tried looking at highcharts document and also simpleisbetterthancomplex class dashboard_view(View): template_name = 'accounts/dashboard.html' def get(self, request, *args, **kwargs): dataset = Profile.objects \ .values('is_active') \ .annotate(is_active_count=Count('is_active', filter=Q(is_active=True)), not_is_active_count=Count('is_active', filter=Q(is_active=False))) \ # categories = list('User') is_active_series_data = list() not_is_active_series_data = list() for entry in dataset: # categories.append('User') is_active_series_data.append(entry['is_active_count']) not_is_active_series_data.append(entry['not_is_active_count']) is_active_series = { 'name': 'Active user', 'data': is_active_series_data, 'color': '#23CE3F' } not_is_active_series = { 'name': 'Inactive user', 'data': not_is_active_series_data, 'color': '#FB3A3A' } chart = { 'chart': { 'type': 'column', 'backgroundColor': '#E3F0E6', 'options3d': { 'enabled': "true", 'alpha': 10, 'beta': 15, 'depth': 50, } }, 'title': {'text': 'Active user on Current Platform'}, 'xAxis': {'categories': ['Active', 'Inactive']}, 'yAxis': { 'title': { 'text': 'No.of users'}, 'tickInterval': 1 }, 'plotOptions': { 'column': { 'pointPadding': 0.2, 'borderWidth': 0, 'depth': 60, } }, 'series': [is_active_series, not_is_active_series] } dump = json.dumps(chart) return render(request, self.template_name, {'chart': dump}) def post(self, request, *args, **kwargs): dataset = Department.objects \ .values('department') \ .annotate(IT_count=Count('department', filter=Q(department="IT")), Sales_count=Count('department', filter=Q(department="Sales")), Admin_count=Count('department', filter=Q(department="Admin")), HR_count=Count('department', filter=Q(department="HR"))) \ .order_by('department') categories = list() IT_series_data = list() Sales_series_data = list() Admin_series_data = list() HR_series_data = list() for entry in dataset: categories.append('%s … -
Custom error messages not working in Django ModelForm
I have a ModelForm and I want to customize some of the error messages for required fields. Some of the customized error messages work, but some don't. Here is my code: error_messages = { 'height': { 'required': _("Your height is required."), }, 'diet': { 'required': _("Your diet is required."), # ~~~~ TODO: not working. }, 'smoking_status': { 'required': _("Your smoking status is required."), # ~~~~ TODO: not working. }, 'relationship_status': { 'required': _("Your relationship status is required."), # ~~~~ TODO: not working. }, **{to_attribute(name='profile_description', language_code=language_code): { 'required': _("Please write a few words about yourself."), } for language_code, language_name in django_settings.LANGUAGES}, **{to_attribute(name='city', language_code=language_code): { 'required': _("Please write where you live."), # ~~~~ TODO: not working. } for language_code, language_name in django_settings.LANGUAGES}, **{to_attribute(name='children', language_code=language_code): { 'required': _("Do you have children? How many?"), } for language_code, language_name in django_settings.LANGUAGES}, **{to_attribute(name='more_children', language_code=language_code): { 'required': _("Do you want (more) children?"), } for language_code, language_name in django_settings.LANGUAGES}, **{to_attribute(name='match_description', language_code=language_code): { 'required': _("Who is your ideal partner?"), } for language_code, language_name in django_settings.LANGUAGES}, 'gender_to_match': { 'required': _("Gender to match is required."), # ~~~~ TODO: not working. }, 'min_age_to_match': { 'required': _("Minimal age to match is required."), }, 'max_age_to_match': { 'required': _("Maximal age to match is required."), }, … -
vh and percentage in CSS?
I'm trying to have the .navbar half of the screen but it is not showing correctly. I'm not sure why? I'm guessing there is another container but i'm not sure why? I set the body to 100vh to cover screen I have .navbar half of that using percentage html file: <!DOCTYPE html> {% load staticfiles %} <html> <head> <link rel="stylesheet" href="{% static "NavBarHtml.css" %}" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body class="all"> <div class="navbar"> <div class="navbarButtons"> <button type="button" class="btn btn-outline-primary">Primary</button> <button type="button" class="btn btn-outline-primary">Primary</button> <button type="button" class="btn btn-outline-primary">Primary</button> <button type="button" class="btn btn-outline-primary">Primary</button> <button type="button" class="btn btn-outline-primary">Primary</button> </div> </div> </body> </html> CSS file: .all{ background-color: red; width: 100vh; height: 100vh; } .navbar{ width: 50%; background-color: white; } .navbarButtons{ background-color: aqua; } -
Getting "object of type 'bool' has no len()" when trying to add category in Django after deploying to Heroku
I've recently deployed my Django app to Heroku, and after trying to add a category in admin from the model Category, I get the type error "object of type 'bool' has no len()" Like I said this is after deploying to Heroku. When hosting locally, everything was working fine with no errors. I tried to reset the Postgres database and run migrations again, but still get the same error. Here are my models: # models.py from django.db import models from django.utils.translation import ugettext_lazy as _ class Category(models.Model): name = models.CharField(max_length=200, blank=True) slug = models.SlugField(blank=True) def __str__(self): return self.name class Meta: verbose_name = "categories" verbose_name_plural = "categories" Here is the traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper 606. return self.admin_site.admin_view(view)(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner 223. return view(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/options.py" in add_view 1634. return self.changeform_view(request, None, form_url, extra_context) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, …