Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
0 vs None: 0 should still be inside my if-call
I write in my template: {% if ticket_price.discounted_price %}. Now that works perfect, until ticket_price.discounted_price = 0. As 0 can happen (original price = 10, discount = 10 > discounted_price = 0) if want to include this option. However, it seems if ticket_price.discounted_price 'thinks' 0 is equal to None. How would you solve that? -
django send email recipient_list
I need to get the email registered in the database and send to this email that is registered, but I can not. If I put an email manually it is sending without problems, but I need it to get the email that is registered in Pessoa to use in MovRotativo to send the payment as soon as it is done models.py from django.db import models from django.core.mail import send_mail import math PAGO_CHOICES = ( ('Não', 'Não Pago'), ('Sim', 'Pago') ) class Pessoa(models.Model): nome = models.CharField(max_length=50, blank=False) email = models.EmailField(blank=False) cpf = models.CharField(max_length=11, unique=True, blank=False) endereco = models.CharField(max_length=50) numero = models.CharField(max_length=10) bairro = models.CharField(max_length=30) telefone = models.CharField(max_length=20, blank=False) cidade = models.CharField(max_length=20) estado = models.CharField(max_length=2, choices=STATE_CHOICES) def __str__(self): return str(self.nome) + ' - ' + str(self.email) class MovRotativo(models.Model): checkin = models.DateTimeField(auto_now=False, blank=False, null=False,) checkout = models.DateTimeField(auto_now=False, null=True, blank=True) email = models.ForeignKey(Pessoa, on_delete=models.CASCADE, blank=False) valor_hora = models.DecimalField( max_digits=5, decimal_places=2, null=False, blank=False) veiculo = models.ForeignKey( Veiculo, on_delete=models.CASCADE, null=False, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) def send_email(self): if self.pago == 'Sim': send_mail( 'Comprovante pagamento Estacione Aqui 24 Horas', 'Here is the message.', 'estacioneaqui24@gmail.com', recipient_list=[self.email], fail_silently=False, ) -
Error while doing POST 'UserCreationForm' object has no attribute 'is_vaild'
I'm a django learner and I was trying to create user registration form using the in-build UserCreationForm. view.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_vaild(): username = form.cleaned_data['username'] return redirect('blog-home') else: form = UserCreationForm() return render(request, 'users/register.html',{'form':form}) While trying to POST i'm receiving 'UserCreationForm' object has no attribute 'is_vaild'. If i understand correctly for all the django forms there will be a is_valid function to validate. Please help me to find what am i missing here. Let me know if you need any other file details. I'm using Django 2.1,Python 3.6 -
Django group by add non existing choices
I have a model field that contains choices: db_redirection_choices = (('A', 'first'), ('B', 'second')) redirection_type = models.CharField(max_length=256, choices=db_redirection_choices, blank=True, null=True) At some point I'm performing a group by on that column, counting all existing choices: results = stats.values('redirection_type').annotate(amount=Count('redirection_type')).order_by('redirection_type') However, this will give me only results for existings choices. I'd like to add the ones that are not even present with 0 to the results e.g. If the table contains only the entry Id | redirection_type -------------------------- 1 | 'A' then the annotate will return only 'A': 1 of course that's normal, but I'd still like to get all non-existing choices in the results: {'A': 1, 'B': 0} What's the easiest way of accomplishing this? -
How to pass value through unselected checkbox in django forms?
I Used to pass value through selected checkbox <input class="product-active-checkbox" type="checkbox" name="ingredient_id" checked="" value="{{ ingredient.id }}" id="{{ ingredient.id }}"> like wise, I want to pass "0" value through unselected checkbox? Or, Is there any way to identify unselected checkbox in django template? -
Mysqlclient and django issues
I have installed mysql connector , which already has built in sql adapter, i also dont need to install mysqlclient as i have mysql connector. But when i start python manage.py migrate, it is asking me to download mysqlclient. But i can not install mysqlclient. Can anyone help me how to fix the problem. Thanks error: File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\models\base.py", line 101, in new new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\models\base.py", line 305, in add_to_class value.contribute_to_class(cls, name) File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\models\options.py", line 203, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db__init__.py", line 33, in getattr return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\utils.py", line 202, in getitem backend = load_backend(db['ENGINE']) File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "C:\Program Files (x86)\Python37-32\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "C:\Program Files (x86)\Python37-32\lib\site-packages\django\db\backends\mysql\base.py", line 20, in ) from err django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? -
rendering JSON in django template without having to escape the entire JSON?
In my django view I produce a JSON data that my template needs to use: languages = { ... } context = { 'languages': json.dumps(languages) } return render(request, 'template.html', context) Then in the template, instead of just doing var languages = {{languages}}; I need to do this because some strings might break the javascript: var languages = JSON.parse('{{languages|safe|escapejs}}'); Which outputs a messy blob like this: var languages = JSON.parse('[{\u0022name_english\u0022: \u0022Afar\u0022, \u0022code\u0022: \u0022aa\u0022, \u0022name\u0022: \u0022Afar\u0022}, {\u0022name_english\u0022: \u0022Afrikaans\u0022, \u0022code\u0022:... I would really like to have this in my rendered template: var languages = [{"name_english": "Afar", "code": "aa", "name": "Afar"}, {"name_english": "Afrikaans", "code": "af", "name": "Afrikaans"}, {"name_english": "Akan", ... But as I said there is the need for escaping. Is there a way to just escape the strings that really need escaping and not the whole JSON? Thanks -
Event webhook help in python/ django. Authorization error
I have an api to get, create event and update event too.. for now i want to get push notification for if any attendee accepted the event request or rejected it or did any modification to it. so i did followed the link https://developers.google.com/calendar/v3/push and wrote my code as follow. please help if iam going wrong some where. Here user_email is my calenderId. still i am getting 400 or 401 status response saying authorization error event_notification = { "id": event['id'], "type": "web_hook", "address": "http://www.example.com/notifications" }`enter code here` url = "https://www.googleapis.com/calendar/v3/calendars/"+user_email+"/events/watch" response = requests.post(url=url, data=json.dumps(event_notification), headers={"Content-Type":"application/json","Authorization":"I HAVE ENTERED THE ACCESS TOKEN OF CURRENT USER"}) -
Django logging on AWS lambda using Serverless
I'm working on a Django project running on AWS lambda configured using Serverless and having difficulty with logging. My logging config is below. No logs appear in CloudWatch other than the start/stop logs from AWS. There should be a lot of DEBUG-level messages appearing, but none are (no log messages from Django are appearing at all). Any ideas? Thank you! Logging config from settings.py: # Logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s' }, 'error': { 'format': '%(levelname)s <PID %(process)d:%(processName)s> %(name)s.%(funcName)s(): %(message)s' }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'standard', 'level': 'DEBUG', }, }, 'loggers': { '': { 'handlers': ['console'], 'level': 'DEBUG', }, }, } -
Two forms in one model. Combining values for table databases
I have simple model in django that looks like : class TimeTable(models.Model): title = models.CharField(max_length=100) start_time= models.CharField(choices=MY_CHOICES, max_length=10) end_time = models.CharField(choices=MY_CHOICES, max_length=10) day1 = models.BooleanField(default=False) day2 = models.BooleanField(default=False) day3 = models.BooleanField(default=False) day4 = models.BooleanField(default=False) day5 = models.BooleanField(default=False) day6 = models.BooleanField(default=False) day7 = models.BooleanField(default=False) for this model I have 2 forms : class TimeTableForm(ModelForm): class Meta: model = TimeTable fields = ['title ', 'start_time', 'end_time'] class WeekDayForm(ModelForm): class Meta: model = TimeTable fields = ['day1', 'day2', 'day3', 'day4', 'day5', 'day6', 'day7'] Now In views.py I need to save this values into database def schedule(request): if request.method == 'POST': form = TimeTableForm(request.POST) day_week = WeekDayForm(request.POST) if all([form.is_valid(), day_week.is_valid()]): form.save() day_week.save() I'm new in Django so I was thinking that this values will be combined into one and I will get proper data but for every one submit I get two separated objects in database for example title | 8:00 | 10:00 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | | | 0 | 1 | 1 | 1 | 1 | 0 | 0 | but I should get title | 8:00 | 10:00 | 0 | 1 | 1 | 1 | 1 … -
Django passing parameter from views hangs server
I try to make simple web site with django, Oracle DB and django web server. And when I make query to db in django shell: mylist=person.objects.filter(name='Anon') everything works fine. Same when I use in views simple render def index(request): return render(request, 'sos/index.html', {}) I get basic site. But when I try to pass parameters from query: def index(request): mylist=person.objects.filter(name='Anon') return render(request, 'sos/index.html', {'mylist': mylist}) server hangs - no matter which browser I use, website is still connectig - only I can do is ctrl+C. -
Sentry is attempting to send 1 pending error messages in Celery-Beat
I'm getting an error on the celery-beat container. Error Message: Sentry is attempting to send 1 pending error messages Celery-Beat Error Logs: [2018-11-27 12:40:21,139: WARNING/MainProcess] (0, 0): (403) ACCESS_REFUSED - Login was refused using authentication mechanism AMQPLAIN. For details see the broker logfile. [2018-11-27 12:40:21,241: WARNING/MainProcess] Sentry is attempting to send 1 pending error messages [2018-11-27 12:40:21,241: WARNING/MainProcess] Waiting up to 10 seconds [2018-11-27 12:40:21,241: WARNING/MainProcess] Press Ctrl-C to quit celery beat v4.0.2 (latentcall) is starting. __ - ... __ - _ LocalTime -> 2018-11-27 12:40:19 Configuration -> . broker -> amqp://RabbitUser:**@rabbit:5672// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) RabbitMq Logs: =INFO REPORT==== 27-Nov-2018::12:40:19 === closing AMQP connection <0.308.0> (192.168.48.3:36552 -> 192.168.48.4:5672) =INFO REPORT==== 27-Nov-2018::12:40:24 === accepting AMQP connection <0.313.0> (192.168.48.2:56664 -> 192.168.48.4:5672) =ERROR REPORT==== 27-Nov-2018::12:40:24 === Error on AMQP connection <0.313.0> (192.168.48.2:56664 -> 192.168.48.4:5672, state: starting): AMQPLAIN login refused: user 'RabbitUser' - invalid credentials =INFO REPORT==== 27-Nov-2018::12:40:24 === closing AMQP connection <0.313.0> (192.168.48.2:56664 -> 192.168.48.4:5672) According to the log, Is it an authentication error? what is the possible solution? Thanks in advance. -
How to swap django-authtools for django.contrib.auth
I'm currently working on a project which makes use of django-authtools. This is something we want to move away from and to go back to using the django.contrib.auth package. What would be the best way to go about this? I need to preserve all existing user accounts and can't seem to have the auth_user and authtools_user tables co-exist. -
Django (Trying to use pagination with filter)
I am trying to add Pagination to my queryset with filter, filter seems to work but pagination doesn't. Can someone let me know what changes i need to make so that pagination works. When we go onto page 2 we get the whole query result instead of filter Django filer + pagination Below is the code: def index(request): user_list_all = MasterGidrDataDict.objects.all() user_filter = UserFilter(request.GET, queryset=user_list_all) user_list = user_filter.qs page = request.GET.get('page', 1) paginator = Paginator(user_list, 50) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) args = {'paginator': paginator, 'filter': user_filter, 'users': users} return render(request, 'app1/index.html', args) index.html <html> <head> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> </head> {% block content %} <form method="get"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> <div class = "tabl" > <table class = 'table table-bordered'> <thead> <tr> <th style="color:black;"> id </th> <th style="color:black;"> vendor_name </th> <th style="color:black;"> market_name</th> <th style="color:black;"> grup </th> <th style="color:black;"> vrbl </th> <th style="color:black;"> code </th> <th style="color:black;"> output </th> <th style="color:black;"> active_flag </th> <th style="color:black;"> load_date <th> </tr> </thead> <tbody> {% for user in users %} <tr> <td>{{ user.id|upper }}</td> <td>{{user.vendor_name}}</td> <td>{{user.market_name}}</td> <td>{{user.grup}}</td> <td>{{user.vrbl}}</td> <td>{{user.code}}</td> <td>{{user.output}}</td> <td>{{user.active_flag}}</td> <td>{{user.load_date}}</td> </tr> {% endfor %} … -
how to fix it a bytes-like object is required, not 'str' (python)
in my python/django application,i want get information about wallet, but it errors:TypeError: a bytes-like object is required, not 'str', could you please tell me how to solve it views.py: def index(request): get_info_payload = {"jsonrpc": "2.0", "params": [], "id": "2", "method": "info"} rpc_auth = base64.b64encode("%s:%s" % ("admin", "123456")) auth_headers = {'Content-Type': 'application/json', 'Authorization': rpc_auth} post_url = "http://127.0.0.1:8229/rpc" s = Session() req = Request('POST', post_url, json=get_info_payload, headers=auth_headers) prepped = req.prepare() resp = s.send(prepped) return HttpResponse(resp.text) -
Django new application working in dev but not in production (Apache server)
I have a django website working properly in production and dev, recently I downloaded django-tables2 and worked a bit with it with no problem in development on a local server. However when putting it on my production server it gives me error 500 when going to the url. I installed it by doing sudo pip install django-tables2 Here's the error log of apache : [Tue Nov 27 10:32:39.633848 2018] [wsgi:error] [pid 27589:tid 139662681429760] [remote 213.152.28.84:63400] mod_wsgi (pid=27589): Target WSGI script '/home/ubuntu/coding-platform/coding_platform/wsgi.py' cannot be loaded as Python module. [Tue Nov 27 10:32:39.633932 2018] [wsgi:error] [pid 27589:tid 139662681429760] [remote 213.152.28.84:63400] mod_wsgi (pid=27589): Exception occurred processing WSGI script '/home/ubuntu/coding-platform/coding_platform/wsgi.py'. [Tue Nov 27 10:32:39.637556 2018] [wsgi:error] [pid 27589:tid 139662681429760] [remote 213.152.28.84:63400] Traceback (most recent call last): [Tue Nov 27 10:32:39.637611 2018] [wsgi:error] [pid 27589:tid 139662681429760] [remote 213.152.28.84:63400] File "/home/ubuntu/coding-platform/coding_platform/wsgi.py", line 19, in <module> [Tue Nov 27 10:32:39.637618 2018] [wsgi:error] [pid 27589:tid 139662681429760] [remote 213.152.28.84:63400] application = get_wsgi_application() [Tue Nov 27 10:32:39.637627 2018] [wsgi:error] [pid 27589:tid 139662681429760] [remote 213.152.28.84:63400] File "/home/ubuntu/coding-platform/ENV/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Tue Nov 27 10:32:39.637631 2018] [wsgi:error] [pid 27589:tid 139662681429760] [remote 213.152.28.84:63400] django.setup(set_prefix=False) [Tue Nov 27 10:32:39.637639 2018] [wsgi:error] [pid 27589:tid 139662681429760] [remote 213.152.28.84:63400] File "/home/ubuntu/coding-platform/ENV/lib/python3.6/site-packages/django/__init__.py", line 24, in setup [Tue … -
Django - Check if a variable set exists in the Database and process it if it does?
So I have a Django App, where a CSV-File can be uploaded. My CSV-File has 9 columns that can be divided into two "datasets" where the first 5 columns need to be handled as one information and the other 4 need to be handled as another information. I cannot put the first 5 in one cell and the other ones in another cell. I would like to check whether or not the first dataset exists and if it does, process it. The same applies to the other dataset. And if both datasets do not exist already it should just update the Database with get_or_create. Here is my views.py idea def import_csv(request): if request.method == "POST": with open('C:/Users/admin/Desktop/djangoexcel/b.csv') as file: reader = csv.reader(file) for row in reader: var = CSV_File4.objects.filter( attr1=row[0], attr2=row[1], attr3=row[2], attr4=row[3], attr5=row[4], ) if var.exists(): TemplateResponse(request, "documents/replace_entry.html", {'var' : var}) else: for row in reader: switch = CSV_File4.objects.filter( attr6=row[5], attr7=row[6], attr8=row[7], attr9=row[8] ) if var2.exists(): TemplateResponse(request, "documents/replace_entry.html", {'var2' : var2}) else: for row in reader: _, p = CSV_File4.objects.get_or_create( attr1=row[0], attr2=row[1], attr3=row[2], attr4=row[3], attr5=row[4], attr6=row[5], attr7=row[6], attr8=row[7], attr9=row[8] ) return redirect('documents:index') form = UploadFileForm() return render( request, "documents/csv_upload.html", {"form": form} ) It should look something like this. How … -
Django Rest Framework serialization error: Object of type type is not JSON serializable
I am new to both django and python and currently trying to implement a REST api using django-rest-framework. I know there are a lot of alike questions but they are serializing objects using .json, and i am not. I have 2 models captain and boat as follows: //models.py from django.db import models class Captain(models.Model): name = models.CharField(max_length=255, blank=False, unique=False) last_name = models.CharField(max_length=255, blank=False, unique=False) government_id = models.CharField(max_length=55, blank=False, unique=True) company_name = models.CharField(max_length=255, blank=False, unique=False) phone_number = models.CharField(max_length=55, blank=False, unique=False) tax_id = models.CharField(max_length=55, blank=False, unique=True) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) class Boat(models.Model): captain = models.ForeignKey(Captain, on_delete=models.CASCADE, null=True, blank=True, related_name='boats') name = models.CharField(max_length=55, blank=False) journey_type = models.CharField(max_length=55, null=True, blank=True) category = models.CharField(max_length=55, null=True, blank=True) passenger_capacity = models.IntegerField() crew_count = models.IntegerField() have_ac = models.IntegerField(default=0) year_built = models.DateField year_restored = models.DateField(blank=True) engine = models.CharField(max_length=255, blank=True, null=True) generator = models.CharField(max_length=255, blank=True, null=True) width = models.CharField(max_length=255, null=True) height = models.CharField(max_length=255, null=True) length = models.CharField(max_length=255, null=True) wc_count = models.IntegerField(null=True) master_cabin_count = models.IntegerField(null=True) standart_cabin_count = models.IntegerField(blank=False, null=False) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) As you can see each boat has one captain and one captain can have many boats. So in database there is a captain_id field for Boat table. I have defined two serializers for each … -
I am getting valueError when executing migrate
So I am new to Django and I am using a guide to do an easy e-commerce website. The problem I have is that I keep getting an ValueError and I am not sure how to fix this. This is my manage.py file import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rdewebsite.settings.dev") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) And the error I am getting is here: Ernestass-MacBook-Pro:rdewebsite ernekz$ python3 manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 350, in execute self.check() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 60, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/urls/resolvers.py", line 396, in check for pattern in self.url_patterns: File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/urls/resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] … -
Display part of form as_p and other part as_table
I have simple django form. Part of this form I need to display as_p and other part as_table ? Can it be done in one form ? Ofc I can use separated forms and do it easily but when I save two forms to database it gives me separated values like 2 different tables . -
Elasticbeanstalk django projoject deployment decouple link error
I'm getting this error while uploading .ebextension file which containing two file , first config file like this : packages: yum: freetype-devel: [] libffi-devel: [] libpng-devel: [] libjpeg-turbo-devel: [] libevent: [] libevent-devel: [] nginx: [] git: [] ............. ............. Return code: 1 Output: (TRUNCATED)...6/site-packages/decouple.py", line 70, in get raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: FACEBOOK_APP_ID not found. Declare it as envvar or define a default value. container_command 01_migratedb in .ebextensions/02_deploy_app.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. Environment showing red mark. I've used 'python-decouple' package. for that reason I've created .env file where every environment variable are perfectly declared. but aws elastice beanstalk are failed to connect that file, that's why environment variable are not uploading properly, for that issue. any suggestion please ... -
Django Model Table Input
I am trying to insert a data table in my current project. I was wondering if it is possible to insert one whole table inside one particular Django Model. If I let the user fill this table, like in the example below: How could I send that data into my model after POST? -
How to pass queryset for django mommy model with manytomany through field
Now I have product model like that class Product(models.Model): attrs = models.ManyToMany('ProductAttribute', through='ProductAttributeValue') ...some fields Now I want to create some fake data using faker and model mommy like that [mommy.make(Product, title=ff.text(max_nb_chars=25), description=ff.text(max_nb_chars=80), categories=Category.objects.filter(depth=3), product_class=ProductClass.objects.first(), attributes=ProductAttribute.objects.all()) for _ in range(15)] How can I pass ProductAttributeValue.objects.filter(..filters..) to m2m modelmommy recipes or whatever within through field -
Filter object with Vue.js, Axios and Django.
I have a project with Vue.js and Django. I am trying to get a list from a database, with a simple search. In Vue/Axios, I have it: var food = 'CHICKEN' const url = `${API_URL}/api/list_food_composition/${food}`; axios.get(url).then(response => { var data = response.data; console.log(data) }); But the response is 'undefined' In Django, I have it: urls.py url(r'^api/list_food_composition/$', views.list_food_composition), views.py def list_food_composition(request,food): foods = Food_composition.objects.filter(short_description__contains=food) data = serializers.serialize('json', foods) return HttpResponse(data, content_type='application/json') What is the correct way for do it? -
Python Json: adding a varable to construct json
I am trying to build a json response in my def. This is my code so far def createSession(numOfPlayers, catagory_id, is_provided, questions): cred = credentials.Certificate(#somthing here) firebase_admin.initialize_app(cred, { #something here }) db = firestore.client() doc_ref = db.collection(u'Session').document(u'insertedByPython3') str_data = { u'Number_of_players' : numOfPlayers } data = json.dumps(str_data, ensure_ascii=False) doc_ref.set(data) As you can see, I have some inputs to my method and I want to construct a json out of it. Thank you.