Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why result in django RQ become : pickle data was truncated?
i cant fiqure out whats wrong in my code, please help me this is my code, i want to defer queryset to django rq in views.py class PartnerCatalogueView(generic.ListView): """ Browse all products in the catalogue based on vendor """ template_name = 'catalogue/vendorku.html' # paginate_by = 9 model = Product context_object_name = 'prod' def get_queryset(self, **kwargs): queryset = super(PartnerCatalogueView, self).get_queryset() queue = django_rq.get_queue('high', autocommit=True, async=True, default_timeout=360) u = self.kwargs['pk'] a = queue.enqueue(long_runnig_task, u) time.sleep(0.2) queryset = a.result return queryset and this my code in tasks.py @job("high", timeout=360) def long_runnig_task(s): o = Product.objects.filter(stockrecords__partner__id=s) return o in worker terminal i get this result: 18:33:07 high: Job OK (c7f769d0-0d79-426e-8428-c6246ed736bf) 18:33:07 Result: '<ProductQuerySet [<Product: tes>, <Product: OKe>]>' 18:33:07 Result is kept for 500 seconds 18:33:07 Sent heartbeat to prevent worker timeout. Next one should arrive within 420 seconds. 18:33:07 Sent heartbeat to prevent worker timeout. Next one should arrive within 420 seconds. 18:33:07 *** Listening on high,low... 18:33:07 Sent heartbeat to prevent worker timeout. Next one should arrive within 420 seconds. in django terminal i got this results: File "/Users/ibadi/.virtualenvs/myshop/lib/python3.6/site-packages/django/views/generic/list.py", line 160, in get self.object_list = self.get_queryset() File "/Users/ibadi/oke/grosire/apps/catalogue/views.py", line 33, in get_queryset queryset = a.result File "/Users/ibadi/.virtualenvs/myshop/lib/python3.6/site-packages/rq/job.py", line 395, in result self._result = loads(rv) … -
Creating folder with changing foldername under Ubuntu in Django project
I have this code in my project: name = "some-name" myDir = os.path.join(BASE_DIR, r'first_scrapy\spiders\tmp\{}'.format(name)) I am developing on Windows, and this works - it creates a folder with a name what I have set. But when I am deploying this code on Ubuntu 16.04 - this code creates folders with names like first_scrapy\spiders\tmp\parfums-promo - path to the folder becomes a folder name. How can I avoid that? -
Multiple File Uploads Django
I'm a relative n00b and have created a form to upload files based on this guide: Need a minimal Django file upload example I want to adapt this to allow for multiple file uploads. I've tried a couple of approaches without much luck. Any advice appreciated. Upload form <form action="{% url 'list' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload" /></p> </form> views.py def list(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() return HttpResponseRedirect(reverse('list')) else: form = DocumentForm() # A empty, unbound form documents = Document.objects.all() return render( request, 'check/list.html', {'documents': documents, 'form': form} ) forms.py class DocumentForm(forms.Form): docfile = forms.FileField( label='Select a file', help_text='max. 42 megabytes', ) -
file download using django and javascript
i have create a django app with REST JSON API and i fill html table in web page from my JSON. here some examples javascript snippets : var field22=document.getElementById('f22'); field22.innerHTML=e.target.feature.properties.id; var field23=document.getElementById('f23'); field23.innerHTML=e.target.feature.properties.file_1; html : </tbody></table><br> <br> <table style="width:95%"> <tbody><tr> <th align="left">id :</th> <td id="f22"></td> </tr> <tr> <th align="left">file :</th> <td id="f23"></td> </tr> <tr> i have parse my JSON in table with success but in the file field now i have a simple text from image path. Now i want in this path to have some hyperlink(or button) for download this file. any idea how to do this because i stack ?i dont know how to connection javasscript with my download or how to download this file using javascript django app code models.py: class MyModel(models.Model): file_1 = models.FileField(upload_to='documents/',blank=True, null=True) simple test django donwload : def download(request, id): product_file=MyModel.objects.get(pk=id) f = StringIO() zip = zipfile.ZipFile(f, 'w') product_file_url = product_file.file_1.url file_url = settings.MEDIA_ROOT + product_file_url[6:] filename = product_file_url[6:].split('/')[-1] zip.write(file_url,filename) zip.close() response = HttpResponse(f.getvalue(), content_type="application/zip") response['Content-Disposition'] = 'attachment; filename=file-download.zip' return response -
Django submitting two forms with a foreign key
I am trying to submit two forms in one template. With one model key being the foreign key for the other model. The foreign key will be set after the POST has been done. class CustomerSystem(models.Model): ---Some fields--- class MN(models.Model): --some fields-- customer_system_serial_number = models.ForeignKey(CustomerSystem, on_delete= models.CASCADE) This is how my models.py looks like The template file is a standard template with 'form' variable In forms.py I have excluded the customer_system_serial_number from the MN model. This is what I am attempting in views @login_required def add_customers(request): if request.method == 'POST': form_cs = CustomerSystemForm(request.POST, prefix='cs') form_mn = MNForm(request.POST, prefix='mn') if form_cs.is_valid() and form_mn.is_valid(): model_instance = form_cs.save(commit=False) model_instance.save() print(model_instance) form_mn.customer_system_serial_number = model_instance form_mn.save() return HttpResponseRedirect('/database/customers') else: form_cs = CustomerSystemForm(request.POST, prefix='cs') form_mn = MNForm(request.POST, prefix='mn') return render(request, 'database/customer_system.html', {'form_cs': form_cs, 'form_mn': form_mn}) The error I am getting is the not Integrity error/not null error. I can see that the model_instance is being saved since it prints a valid object. I am trying to do something like how to set foreign key during form completion (python/django) However I am clearly missing something probably very basic. Any help is appreciated -
Bootstrap alert closing on page load
I have a view in which I send some messages, like this: messages.warning(request, 'Nothing found") on my template, I display them like this: {% for message in messages %} <div class="alert {{ message.tags }} alert-dismissible fade in"> <button type="button" class="close" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> {% if message.tags == 'info' %} <p>{{ message }}<br> You have <strong>{{users}}</strong> user{{users|pluralize}}<br> ,around <strong>{{non_users}}</strong> non user{{non_users|pluralize}}</p> {% else %} <p>{{ message }}</p> {% endif %} </div> {% endfor %} When the template loads, the messages appears very fast and disappears. If I try this: <p>{{message}}</p> instead the message stays there, so I'm guessing I'm doing something wrong with bootstrap. This (kinda) works as well: <div class="{{message.tags}}"> Could someone shed a light? -
How to update the template object_list using ajax, jinja, django and django rest framework
Its my first time doing a big project with django and first time using ajax too, so if i have something wrong u can correct it, without any problem!! I want to update list of client's names every x seconds using ajax with jquery. I found some solutions but i didn't find a solution that fit on my project... My JQuery amnd ajax: <script type="text/javascript"> setInterval(function(){ console.log('Data passed:'); $.ajax({ url: '/dashboard/ajax/reload_data/', success: function (data){ console.log(data); } }); },10000) My view: def reload_data(request): if request.is_ajax(): b = Jobs.objects.order_by('end_time').reverse()[:10] u = Update.objects.values('nome_cliente').distinct() serializerB = JobsSerializer(b, many=True) serializerU = UpdateSerializer(u, many=True) content = {"backup_info": serializerB.data, "update_info": serializerU.data} data = json.dumps(content) return HttpResponse(data, content_type='application/json') else: raise Http404 My template code: <div id ="update"> <div id="dash1div"> <a href=""> <strong>Updates</strong> </a> </div> <ul> {% for update_info in update_info %} <style type="text/css"> #{{update_info.nome_cliente}}:visited, #{{update_info.nome_cliente}}:hover, #{{update_info.nome_cliente}}:focus, #{{update_info.nome_cliente}}:active, #{{update_info.nome_cliente}}{ text-decoration:none; color:#B1EBF9; font-size: 1em; outline: 0; } </style> <li> <a id = "{{update_info.nome_cliente}}" href="/dashboard/ListUpdate/{{update_info.nome_cliente}}/">{{update_info.nome_cliente}}</a> </li> {% endfor %} </ul> </div> I'm already receiving the data but i can't change the template information without refresh the page(that isn't not effective)! Ty for wasted your time helping me :D !!! -
cookiecutter-django docker-compose -f production.yml up hangs
I created a cookiecutter-django app and left it pretty much pain vanilla. Except because I need to run on EC2, behind and Elastic Load Balancer with an SSL cert from AWS Certificate manager, I need to use nginx instead of Caddy. Here's my production.yml: version: '2' volumes: postgres_data: {} postgres_backup: {} services: nginx: build: context: . dockerfile: ./compose/production/nginx/Dockerfile env_file: .env ports: - "0.0.0.0:80:80" depends_on: - django django: build: context: . dockerfile: ./compose/production/django/Dockerfile image: pulsemanager_production_django depends_on: - postgres - redis env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres - ./.env command: /gunicorn.sh postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: pulsemanager_production_postgres volumes: - postgres_data:/var/lib/postgresql/data - postgres_backup:/backups env_file: - ./.envs/.production/.postgres redis: image: redis:3.2 Here's my .env file: # General # ------------------------------------------------------------------------------ # DJANGO_READ_DOT_ENV_FILE=True DJANGO_SETTINGS_MODULE=config.settings.production DJANGO_SECRET_KEY=randomdjangosecretkey DJANGO_ADMIN_URL=djangoadminurl/ DJANGO_ALLOWED_HOSTS=.pulse.example.com # Security # ------------------------------------------------------------------------------ # TIP: better off using DNS, however, redirect is OK too DJANGO_SECURE_SSL_REDIRECT=False # Email # ------------------------------------------------------------------------------ DJANGO_MAILGUN_API_KEY=randommailgunkey DJANGO_SERVER_EMAIL=randomserver@gmail.com MAILGUN_SENDER_DOMAIN=mg.example.com # AWS # ------------------------------------------------------------------------------ DJANGO_AWS_ACCESS_KEY_ID=randomawskeyid DJANGO_AWS_SECRET_ACCESS_KEY=randomawssecretkey DJANGO_AWS_STORAGE_BUCKET_NAME=pulsemanager # django-allauth # ------------------------------------------------------------------------------ DJANGO_ACCOUNT_ALLOW_REGISTRATION=True # Gunicorn # ------------------------------------------------------------------------------ WEB_CONCURRENCY=4 # Sentry # ------------------------------------------------------------------------------ DJANGO_SENTRY_DSN=randomsentrydsn # Redis # ------------------------------------------------------------------------------ REDIS_URL=redis://redis:6379/0 # PostgreSQL # ------------------------------------------------------------------------------ POSTGRES_HOST=postgres POSTGRES_PORT=5432 POSTGRES_DB=pulsemanager POSTGRES_USER=randouserid POSTGRES_PASSWORD=randompassword # Caddy # ------------------------------------------------------------------------------ DOMAIN_NAME=pulse.example.com docker-compose -f production.yml up works fine. docker-compose -f production.yml up might be mostly working, but … -
Jinja 2 - rendering returns Killed docker container
I am attempting to render a Jinja template however when I run the function just returns: >>> file_data = local_config.render(template_data) Killed So im running ./manage.py shell. pasting in my code to test it and then when I go to render the shell is killed env = Environment(autoescape=False, optimized=False) env.filters['octect'] = octect env.filters['mask'] = mask env.filters['host'] = host env.filters['host_first'] = host_first env.filters['host_last'] = host_last env.filters['host_no'] = host_no env.filters['format_date'] = format_date device_data = Device.objects.get(id=device_id) template = device_data.template local_config = env.from_string(template.config) ... code that creates dictionary named template_data ... file_data = local_config.render(template_data) I have a near identical template to this one and that one runs successfully. why would a kill happen? Thanks -
Django-allauth - How to enable to use same email address for difference account
I want to enable user to login with username / password. I also want to allow user to enter email address for email verification use. Here is my settings.py ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = False ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_AUTHENTICATION_METHOD = 'username' ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username' ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_EMAIL_VERIFICATION = 'mandatory' However, when I try to register. There will be an error message. (1062, "Duplicate entry 'test@test.com' for key 'email'") And I found that, there is a new entry in "auth_user" table. But it can't write to "account_emailaddress" table. Also, I found that there is a configure in mysql for "account_emailaddress" UNIQUE KEY `email` (`email`), How can I disable the unique email setting? I'm using python 3.4, django 2.0, django-allauth 0.35 Thanks! -
Store the same django model object in two database tables
I have two model objects like this. A RecordObject which gets updated daily and a RecordHistory table which stores all the updates/ changes to a RecordObject. class RecordObject(models.Model): status = models.CharField() collection_date - models.CharField() class RecordHistory(models.Model): status = models.CharField() collection_date - models.CharField() I want to store the RecordObject in the RecordHistory table with all the updates. How can I store the RecordObject in the RecordHistory table without creating new RecordHistory objects? -
_mysql_exceptions.OperationalError: (1045, "Access denied for user 'vivekmehra88'@'localhost' (using password: NO)")
I am getting below error after setting mysql connection configuration. I have configured database in settings.py with below details DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'read_default_file': '/etc/mysql/my.cfg', } } my.cnf file contains below details [client] database = blog_data host = localhost user = vivekmehra88 password = ******* default-character-set = utf8 After setting database connections I tried to run server, but its giving below error an exception that is caused due to some other exception. myenv) vivekmehra88@vivekmehra88-HP-Pavilion-TS-15-Notebook-PC:~/PycharmProjects/myProj/my_blog_app/blog$ python3 manage.py runserver 127.0.0.1:8000 Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f87a2ded510> Traceback (most recent call last): File "/home/vivekmehra88/PycharmProjects/myProj/my_blog_app/myenv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/home/vivekmehra88/PycharmProjects/myProj/my_blog_app/myenv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/home/vivekmehra88/PycharmProjects/myProj/my_blog_app/myenv/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 236, in get_new_connection return Database.connect(**conn_params) File "/home/vivekmehra88/PycharmProjects/myProj/my_blog_app/myenv/lib/python3.5/site-packages/MySQLdb/__init__.py", line 86, in Connect return Connection(*args, **kwargs) File "/home/vivekmehra88/PycharmProjects/myProj/my_blog_app/myenv/lib/python3.5/site-packages/MySQLdb/connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (1045, "Access denied for user 'vivekmehra88'@'localhost' (using password: NO)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/vivekmehra88/PycharmProjects/myProj/my_blog_app/myenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/vivekmehra88/PycharmProjects/myProj/my_blog_app/myenv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/home/vivekmehra88/PycharmProjects/myProj/my_blog_app/myenv/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/vivekmehra88/PycharmProjects/myProj/my_blog_app/myenv/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/vivekmehra88/PycharmProjects/myProj/my_blog_app/myenv/lib/python3.5/site-packages/django/core/checks/registry.py", line … -
Django Rest Framework batch requests
I am trying to make a batch endpoint in Django Rest Framework, in the spirit of Google's batch requests. To do that, the endpoint uses TokenAuthentication and asks for a json-encoded list of dictionaries with path, method and data if necessary, like this: [ { "path": "/endpoint1", "method": "GET" }, { "path": "/endpoint2", "method": "GET" }, { "path": "/endpoint3", "method": "POST", "data": { "file": "<base64>" } } ] The view iterates the list, copies the request (with the token), sets path and method according to each item and gets a response by resolving the path. Here's the code: from copy import copy @api_view(["POST"]) @authentication_classes((TokenAuthentication,)) @permission_classes((IsAuthenticated,)) def batch(request): operations = request.data responses = [] for operation in operations: op_request = copy(request._request) op_request.path = operation["path"] op_request.method = operation["method"] view, args, kwargs = resolve(operation["path"]) response = view(op_request, *args, **kwargs) operation["response"] = { "status": response.status_code, "data": response.data } return Response(operations) The problem I am coming across is that the authentications headers are not the same to the dispatched views. That is, the regular response for /endpoint3 , when sending a file (with a user token) is a successful response: { "id": "asdf", "name": "asdf.txt", } But when run in batch it ends like this: … -
Django admin ignores has_delete_permission
I have simple project on Django 1.11.13, that uses ordinary Django's admin module. Staff user can not delete object while is permitted (has_delete_permission returns always true). models.py: class MyModel(models.Model): name = models.IntegerField("Value", blank=True, null=True) admin.py: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): def has_add_permission(self, request): return True def has_change_permission(self, request, obj=None): return True def has_delete_permission(self, request, obj=None): return True I created user and logged in. He can create MyModel object (as expected), can edit (as expected), but can not delete!! That's what I see if I try to delete it: Deleting the selected my model would result in deleting related objects, but your account doesn't have permission to delete the following types of objects: my model What am I doing wrong? How should I give permissions to delete MyModels to ordinary staff user? -
Long Django process without implementing Celery, Redis, etc
I have a Django view that takes maybe 1.5 min. to run. It is a relatively small part of my site, and I cannot implement Celery, Redis, or any other 3rd party queuing system—this must be done from within my current build. I'd like to do two things (that would complement one another). (1) Ensure the User isn't timed out while the process is running (2) Implement a loading page or waiting page of some sort [if I can do (2), (1) will be fulfilled]. Once begun, the process must finish—this means it cannot be split into smaller processes that check in with the client, because the whole process would cease upon the user closing his/her browser. As it is now, view: config calls a template wherein a user clicks a "Run" button, and upon clicking this button, view: run is called. view: run is the view that takes about 1.5 min. I've tried view: config redirecting to a JavaScript template page, which itself calls view: run using window.location, but there's nothing the script could do while view: run is running. Could someone help me out? There's a lot to process here, and I'd like some direction. Something I've considered … -
Django: Custom User Model fields not appearing in Django admin
I'm trying to add some extra fields into the django.contrib.auth.models User model. I'll be using this custom User model throughout my project. I used AbstractUser to add name and contact fields. class User(AbstractUser): name = models.CharField(_('Name of User'), blank=True, max_length=255) contact = models.CharField(max_length=20, blank=True) def __str__(self): return self.username In my settings.py, I added to the apps.authentication, which is my app: INSTALLED_APPS = [ 'apps.authentication', ...] I also specified my AUTH_USER_MODEL: AUTH_USER_MODEL = 'authentication.User' I then ran migrations and it worked (I checked my local db; new tables were made). However, when I access it using the Django admin, the name and contact fields were nowhere to be found. How do I make the fields appear? -
Run Scrapy in production
I am trying to deploy Django+Scrapy project. And now I am stucked on the problem - how to run Scrapy on production correctly? I am deploying on Ubuntu 16.04. 1) I have changed my scrapy.cfg file, like this: [settings] default = first_scrapy.settings [deploy] url = http://"my_ip" username = "username" password = "my_password" project = first_scrapy 2) If I run scrapyd on the server - I see: [-] Loading .....lib/python3.5/site-packages/scrapyd/txapp.py... [-] Scrapyd web console available at http://"my_ip" [-] Loaded. [twisted.scripts._twistd_unix.UnixAppLogger#info] twistd 17.9.0 (/home/chiefir/bin/python3 3.5.2) starting up. [twisted.scripts._twistd_unix.UnixAppLogger#info] reactor class: twisted.internet.epollreactor.EPollReactor. [-] Site starting on "my_port" [twisted.web.server.Site#info] Starting factory <twisted.web.server.Site object at 0x7f49fe21d438> [Launcher] Scrapyd 1.2.0 started: max_proc=4, runner='scrapyd.runner' But when I try to run a spider via django admin (I have a system written for that) - it fails. And I see in scrapy.log(shortened error): .......... File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting ',' delimiter: line 17 column 1 (char 531) scrapy.utils.signal: Error caught on signal handler: <bound method SuperSpider.spider_closed of <mySpider 'parfums-promo' at 0x7f48a8baacf8>> Traceback (most recent call last): File "..../lib/python3.5/site-packages/twisted/internet/defer.py", line 150, in maybeDeferred result = f(*args, **kw) File ".../lib/python3.5/site-packages/pydispatch/robustapply.py", line 55, in robustApply return receiver(*arguments, **named) File "..../super_spider.py", line 105, in spider_closed … -
front end validation breaks after adding javascript to form post
Prior to adding the following javascript to my form my form validation adding required to the control was working correctly. Below is my javascript: function submitForm(action) { var form = document.getElementById('form1'); form.action = action; form.submit(); } On the update button I want my form to submit regardless of the selections the user makes. However, on the submit button at the end of the form I want the http form validation to occur. {% extends 'base.html' %} {% load static %} {% block head %} <title> Profile </title> {% endblock %} {% block content %} {% block extra_js %} {{ block.super }} {{ form.media }} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" /> <link href="{% static '/search/hidediv.css' %}" rel="stylesheet" /> <script src= "{% static '/search/dualbuttonsubmit.js' %}" type="text/javascript"></script> <form id = "form1" method= "post"> {% csrf_token %} <div class="well"> <h4 style="margin-top: 0"><strong> User Details </strong></h4> <div class="row"> <div class="form-group col-md-4"> <label/> 3-4 User ID <input class="form-control" type="text" name = "userpost" value= "{{employee.employeentname}}" readonly> </div> <div class="form-group col-md-4"> <label/> First Name <input class="form-control" type="text" value= "{{employee.employeefirstname}}" readonly> </div> <div class="form-group col-md-4"> <label/> Last Name <input class="form-control" type="text" value = "{{employee.employeelastname}}" readonly > </div> <div class="form-group col-md-4"> <label/> Coid <input class="form-control" type="text" value … -
Framework for map display and drawing on Joomla
I'm new on Python. I'm trying to create an web page that needs to do these thinks: 1) Display a google map with the elevation data layer 2) give te possibility to search for a place 3) Give the possibility to draw a polygon 4) Give the area of the polygon and perform some calculations The web server is driven by Joomla. What is the right framework to do that? Django and google map API's GDAL and Mapnik? Other frameworks? Thank you in advance -
Reverse with argument ('')not found. Variable doesnt work
I can't figure out why my url doesn't work together with my variable. This way <form method="post" action="{% url 'p4_descriptor_update' 1 form.instance.pk %}" class="js-descriptor-update-form"> it works, but this <form method="post" action="{% url 'p4_descriptor_update' projectid form.instance.pk %}" class="js-descriptor-update-form"> results in: Reverse for 'p4_descriptor_update' with a rguments '('', 249)' not found. 2 pattern(s) tried I can call {{ projectid }} in my template and it shows the correct number (which is 1) urls.py url(r'^ajax/(?P<id>[0-9]+)/(?P<pk>\d+)/p4_descriptor_update/$', views.p4_descriptor_update, name='p4_descriptor_update'), views.py class phase4 (APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'szenario/phase4.html' def get(self, request, id, format=None): projectid = id context = {... 'projectid': projectid} return Response(context) Not sure if relevant, but the button is not in the main template but included with {% incldue .. %}. If needed i can add the JS or any further information needed. -
django Field.choices read from a single file
I have a Field.choices in my model. lets say it is: YEAR_IN_SCHOOL_CHOICES = ( ('FR', 'Freshman'), ('SO', 'Sophomore'), ('JR', 'Junior'), ('SR', 'Senior'), ) MEDIA_CHOICES = ( ('Audio', ( ('vinyl', 'Vinyl'), ('cd', 'CD'), ) ), ('Video', ( ('vhs', 'VHS Tape'), ('dvd', 'DVD'), ) ), ('unknown', 'Unknown'), ) I can access them using this method Model. YEAR_IN_SCHOOL_CHOICES but how can I save all of them into one single file and use them across my models? is it even possible? I mean I want to have a python file named mychoise.py and save all choices in there and then access them in this way year_in_school = models.CharField( max_length=2, choices=mychoise.YEAR_IN_SCHOOL_CHOICES, default=FRESHMAN, ) -
Django model.parameters
I'm going through a tough time trying to understand a part of the code I was given to review: model.parameters.first() It's a Django model,and though I know what the outcome is, I can't seem to find any word on "parameters" part. I would be so grateful if you could either explain what does the "parameter" function do, or drop a link with the explanation. I couldn't find it anywhere in django documentation. Thanks! -
django template for loop - iterate over element
I want to implement something like this: {% for item in items %} {% for element in item.somefield %} <Work with this element> {% endfor %} {% endfor %} How can I achieve this using Django template? Thanks. -
Sorting of Users Dropdown list (ForeignKey) in Django Admin
I'm using the django admin and want to sort (by last_name) the dropdown list of users in a related field (ForeignKey). I'm am using the standard User model in django. I tried the following in the model.py which is not working: ... from django.contrib.auth.models import User class Meta: ordering = ['last_name'] User.add_to_class("Meta", Meta) ... class Application(models.Model): ... user = models.ForeignKey(User, ... Why is this not working? Is there another (easy) way to do it? I probably should have gone for a custom user model. But I didn't do that and changing it now is seams a lot of work. I am using django 2.0.5 with python 3.6.5 Any help is appreciated. -
Alternative for website scraping and RSS feed
I'm building a django website that "consolidates" news from different websites.Currently I'm using feedparser to retrieve the news from RSS but nowadays some news portal don't provide a RSS feed furthermore the feed changes from website to website.I thought about using a website scraper/crawler to get this information but I think I may have legal issues.Is there a legal alternative to do this?Thanks a lot.