Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to annotate count based on nested JSONField in Django 1.11 and postgres 9.6
My model currently looks like: class Review(models.Model): source = models.CharField(max_length=80, blank=True, null=True) metadata = JSONField(default=dict) entity_type = models.CharField(max_length=255, blank=True, null=True) Example object of class Review: { "source": "amazon", "entity_type": "media", "metadata": [ { "product": 123456 }, { "product": 012345 } ] } I want to annotate count based on "source", "entity_type", "metadata_product" I am talking about Django query similar to: Review.objects.filter().values( "source","entity_type","metadata__product" ).annotate(count=Count('id')) which will obviously not work. I want to get output query set similar to: [{"source": "amazon", "entity_type": "media", "metadata_product": 123456, "count": 1}, {"source": "amazon", "entity_type": "media","metadata_product": 012345, "count": 1}] I want to achieve this using Django ORM and not resort to python because the table contains data close to 10 or 20 million. If that is not possible it will be really good if someone can suggest raw SQL query which can be put in Django ORM raw SQL method. -
uwsgi segmentation fault when serving a django application
I am trying to migrate a django application from one server to another. The application is working fine on the old server. On the new server, the application works fine when used using Django's runserver. To test the django application under uwsgi, I used uwsgi --http :8000 --module mysite.wsgi This opens the django admin page as expected but as soon as I try to login, uwsgi gets a segmentation fault error which is as follows. Would greatly appreciate if anybody could help understand what this means, and how might I fix this. *** uWSGI is running in multiple interpreter mode *** spawned uWSGI worker 1 (and the only) (pid: 15398, cores: 1) !!! uWSGI process 15398 got Segmentation Fault !!! *** backtrace of 15398 *** uwsgi(uwsgi_backtrace+0x35) [0x5569e2f17555] uwsgi(uwsgi_segfault+0x23) [0x5569e2f17903] /lib/x86_64-linux-gnu/libc.so.6(+0x35fc0) [0x7f0dd221bfc0] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/./libssl-1d6df745.so.1.0.2p(ssl3_cleanup_key_block+0xb) [0x7f0dd0241cab] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/./libssl-1d6df745.so.1.0.2p(ssl3_clear+0x16) [0x7f0dd023f5a6] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/./libssl-1d6df745.so.1.0.2p(tls1_clear+0x9) [0x7f0dd024b219] /usr/lib/x86_64-linux-gnu/libssl.so.1.1(SSL_new+0x43f) [0x7f0dd2bf376f] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(+0x23969) [0x7f0dd04d6969] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(+0x24fc5) [0x7f0dd04d7fc5] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(PQconnectPoll+0xb78) [0x7f0dd04c1ba8] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(+0xfa28) [0x7f0dd04c2a28] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/.libs/libpq-3a62a61f.so.5.11(PQconnectdb+0x1f) [0x7f0dd04c541f] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/_psycopg.cpython-36m-x86_64-linux-gnu.so(+0x12651) [0x7f0dd0716651] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/_psycopg.cpython-36m-x86_64-linux-gnu.so(+0x133df) [0x7f0dd07173df] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x1fcab2) [0x7f0dd25d9ab2] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyObject_FastCallDict+0x89) [0x7f0dd2645e99] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyObject_CallFunction_SizeT+0x124) [0x7f0dd26468b4] /home/vikas/ssersurvey/env/lib/python3.6/site-packages/psycopg2/_psycopg.cpython-36m-x86_64-linux-gnu.so(+0xc1a8) [0x7f0dd07101a8] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(PyCFunction_Call+0x96) [0x7f0dd25f0fe6] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x7940) [0x7f0dd2561f10] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17ba3f) [0x7f0dd2558a3f] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(PyEval_EvalCodeEx+0x3e) [0x7f0dd25594fe] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x23cc63) [0x7f0dd2619c63] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(PyObject_Call+0x48) [0x7f0dd26466d8] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x3de5) [0x7f0dd255e3b5] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17a8a3) [0x7f0dd25578a3] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c2eb) [0x7f0dd25592eb] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17a8a3) [0x7f0dd25578a3] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c2eb) [0x7f0dd25592eb] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17a8a3) [0x7f0dd25578a3] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c2eb) [0x7f0dd25592eb] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17ba3f) [0x7f0dd2558a3f] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17c11e) [0x7f0dd255911e] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(_PyEval_EvalFrameDefault+0x4ec2) [0x7f0dd255f492] /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0(+0x17a8a3) … -
How to write unit tests for csv file upload method in django
I've written a method for csv file upload in django now I'm trying to write unit tests for that method. can we mock csv file using from django.core.files.uploadedfile import SimpleUploadedFile, or should I use something else? Can someone discuss that what approach(mocking, upload) should I follow for this problem? -
Django form prefix separator hyphen to underscore
The naming process for django-formtools seems to be breaking the ability to access variables in session data. The form I have named patient_details but it's fields are being separated by - for example patient_details-upper_arch. I'm trying to access the session data to manipulate a form further along in the wizard based on a selection in the first form. However when trying to access {{ ...patient_details-upper_arch }} it throws a TemplateSyntaxError Could not parse the remainder: '-upper_arch' from ...patient_details-upper_arch Is there a way to set the separator to an underscore to make this variable accessible in the template, or another way around this? -
redirect to account activation resend url if user is not active
My forms.py : class UserLoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs= {'class':'form-control form-control-lg','placeholder':'Username'})) password = forms.CharField(widget=forms.PasswordInput(attrs= {'class':'form-control form-control-lg','placeholder':'Password'})) def clean(self, *args, **kwargs): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") if username and password: user = authenticate(username=username, password=password) if user is None: raise forms.ValidationError("This user does not exist") elif user is not None: if not user.is_active: raise forms.ValidationError("This user is not longer active.") elif not user.check_password(password): raise forms.ValidationError("Incorrect password") return super(UserLoginForm, self).clean(*args, **kwargs) I want the user to be redirected to the resend activation link page if he hasnt activated already .Now after i register the user and skip account activation and then try to login ,it shows validation error "This user does not exist" eventhough this user is registered in the User model . -
Django DRF APITestCase chain test cases
For example I want to write several tests cases like this class Test(APITestCase): def setUp(self): ....some payloads def test_create_user(self): ....create the object using payload from setUp def test_update_user(self): ....update the object created in above test case In the example above, the test_update_user failed because let's say cannot find the user object. Therefore, for that test case to work, I have to create the user instead test_update_user again. One possible solution, I found is to run create user in setUp. However, I would like to know if there is a way to chain the test cases to run one after another without deleting the object created from previous test case. -
Validate form and formsets with django
I'm trying to set my form validation in my view and I would like to get you help because I have a little issue. This is my formset : DocumentFormSet = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1, max_num=4, can_delete=True) This is my code : def get_context_data(self, **kwargs): context = super(PublicationCreateView, self).get_context_data(**kwargs) document_queryset = Document.objects.all() context['FormSets'] = DocumentFormSet(self.request.POST or None, self.request.FILES or None, prefix='doc', queryset=document_queryset) return context def form_valid(self, form): try: context = self.get_context_data() formsets = context['FormSets'] if form.is_valid(): self.object = form.save(commit=False) if formsets.is_valid(): formsets.instance = self.object formsets.save(commit=False) for element in formsets: element.save(commit=False) self.object = form.save() formsets.save() return super(PublicationCreateView, self).form_valid(form) except IntegrityError: ... I read some things, especially form has to be save before forms in formset if there is ForeignKey between form and forms in my formset. The issue comes if I have wrong field in my formset. As the first form is saved, it creates an object with only the first form and not with the associated form in my formset. This is an example : As you can see, it saves my first form, but I don't want until all the formset is valid. I have to switch between .save(commit=False) and .save() methods. Thank you -
Multi select in django
I am very new in Django, I want to create an API which shows me cities of selected states,but more than one state I created this view: def get(self,request,State_id1,State_id2): cities = city.objects.filter(state__in= [State_id1,State_id2]) I have two problem here: 1. how to correct this view because user may not select only two states,there may be more than one states 2. how should I define urlpattern -
convert double to time in python
I have a TimeField() in my django models. I want to convert the sum of the record of this to hours. Here's my actual code into my view: hours_week_decimal = Timesheet.objects.filter(owner = request.user.pk, week = datetime.datetime.now().isocalendar()[1]).aggregate(total=Sum('working_hour')) # this method return a dict of decimal total_hours_week = convertDecimalToHours(hours_week_decimal) and the related function: def convertDecimalToHours(times): total_time = 0 for k, v in times.items(): total_time += int(v) print("type: {} - value: {}".format(type(total_time), total_time)) He returned me: type: int - value: 166000 I have two hours: Monday (08:30) and Tuesday(08:30), so he must returned me "17:00" Hope you can help me to pass this problem :) -
Reverse relationships in Nested serializer in django rest framework
My models.py is as as follows: class Group(models.Model): name = models.CharField(max_length=50, unique=True) class Policy(models.Model): name = models.CharField(max_length=50, unique=True) source_group = models.ForeignKey(Group, related_name='source_group') destination_group = models.ForeignKey(Group, related_name='destination_group') Since I have two foreign keys, pointing to the same model, I am using related name to avoid clashes. Now, when I try to create a serializer for Groups in order to list all Policies associated with it, I do the following: class PolicySerializer(serializers.ModelSerializers): class Meta: model = Policy fields = "__all__" class GroupSerializer(serializers.ModelSerializer): policy = PolicySnippetSerializer(source ='source_group', many=True) class Meta: model = Group fields = ['id', 'name', 'policy'] However, this will give me only policies for a a source_group.How did i get all groups associated with a group, source and destination ? -
add django paginator on records
This is my record app views.py, i want to add pagination on result of records list, the list generated by following code and also give solution for templates. Please help me. Thank you. from django.shortcuts import render from purchase_report.views import * import datetime from datetime import datetime from purchase_report.models import * from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def display_records(request): start_date = request.GET.get('start_date') end_date = request.GET.get('end_date') purchase_date = PurchaseReport.objects.filter(purchase_date__range=[start_date, end_date]) return render(request, 'records.html', {'purchase_date': purchase_date, 'start_date': start_date, 'end_date': end_date}) parsed_start_date = None parsed_end_date = None if start_date and end_date: errors = {} try: parsed_start_date = datetime.datetime.strptime(start_date, "%d/%m/%Y") except ValueError: errors["start_date"] = "Invalid date" try: parsed_end_date = datetime.datetime.strptime(end_date, "%d/%m/%Y") except ValueError: errors["end_date"] = "Invalid date" if parsed_start_date and parsed_end_date: purchase_date = PurchaseReport.objects.filter(purchase_date__range=[parsed_start_date, parsed_end_date]) else: purchase_date = PurchaseReport.objects.none() return render(request, 'records.html', {'purchase_date': purchase_date, 'start_date': start_date, 'end_date': end_date, 'errors': errors})