Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms error when submit
i am Beginner django when i click add in form the name sort as a false in database what i can do to avoid this problem views : def addTeam(request) : team1=team() team1.name=request.POST['name'] team1.logo = request.POST['logo'] team1.save() return redirect("https://www.google.ps") urls : url(r'^add/$', views.addTeam, name='team-add') form as a modal :: <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times; </button> <h4 class="modal-title">Add team</h4> </div> <div class="modal-body"> <form action="" method="post"> {% csrf_token %} <input type="text" name="name" id="name" /> <label for="name"> </label> <br> <input type="text" name="logo" id="logo"> <label for="logo"> </label> <br> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data- dismiss="modal">Close</button> <a href="{% url 'team-add' %}"> <button type="button" class="btn btn- default" >add</button></a> </div> </div> </div> </div> -
Dynamic Facebook Like
I have a news app on my website. I added a Facebook like button on every news/post page but i can’t get it working correctly. When I click on the like button, it changes state which is ok but changes are not affected - displayed on the actual Facebook page. Can anybody share their experiences? This is what i tried so far <div class="fb-like" data-href="https://www.facebook.com/mysite.com/posts/" data-layout="button" data-action="like" data-size="large" data-show-faces="false" data-share="true"> </div> and <div class="fb-like" data-href="https://www.facebook.com/mysite.com/news/{{ object.title }}" data-layout="button" data-action="like" data-size="large" data-show-faces="false" data-share="true"> </div> -
'sqlite3.OperationalError: no such table: bossoidc_keycloak' when trying to connect Django app to Keycloak
I am trying to do sign on to my Django app using Keycloak. I have been looking at this blog post but when I have signed in to Keycloak and get redirected back to my Django app my Django app throws this error in my face: App 62 stderr: ERROR Internal Server Error: /openid/callback/login/ App 62 stderr: Traceback (most recent call last): App 62 stderr: File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 65, in execute App 62 stderr: return self.cursor.execute(sql, params) App 62 stderr: File "/usr/local/lib/python3.5/dist-packages/django/db/backends/sqlite3/base.py", line 328, in execute App 62 stderr: return Database.Cursor.execute(self, query, params) App 62 stderr: sqlite3.OperationalError: no such table: bossoidc_keycloak I have run: manage.py makemigrations bossoidc djangooidc manage.py migrate So I don't understand why the table is no there. Does anyone know anything about this? -
Django ImageField not deleted if default is set
Model: class MyModel(models.Model): watermark_image = models.ImageField(null=True, blank=True, default=settings.WATERMARK_DEFAULT) When I try to empty the field in the admin clicking on its checkbox, file is not deleted unless i remove default attribute from model! Why? -
__init__() got an unexpected keyword argument 'instance' in django at the time of form editing with image field in django
forms.py class edit_product_data_check(forms.Form): class Meta: model = product_data fields = '_all_' views.py def update_product_data(request): if request.method == "POST": # Get the posted form p_id=request.POST.get("product_id", "") product_edit = get_object_or_404(product_data, id=p_id) form = edit_product_data_check(request.POST, request.FILES, instance=product_edit) if form.is_valid(): form.save() HttpResponseRedirect(reverse('index')) return HttpResponseRedirect(reverse('product'))` -
Recommend stack for my python app
I wrote a Python script which checks the price of a stock and sends an SMS when the price increased or decreased by a certain amount within a day. The process is repeated every 10 minutes. At the moment it uses a the sleep function but it might be better off with a cron job. I want to run this app on a raspberry I want to build a web interface which shows the status and has a kill switch Can you recommend a stack to use for this? I started working in Django but I've realized that I need to plan this better. -
Django REST Framework Serializer output
I'am new to Django and DRF, but I'am trying to use DRF's Serializer to override djosers default user registration behavior. (djoser = a DRF lib for user registration/login/password reset etc.) I've djosers view, that uses a serializer to create user objects def perform_create(self, serializer): user = serializer.save() My idea was to override this serializer to achieve the following: create the user create an account object in parallel login the user return the account object alongside with the auth token in one response The last point gives me trouble because I don't know how to achieve such custom behavior in the serializer. I made the input fields readonly, so they are not included in my response. In the save method a create a user + account object, logging in the user and then I return the user (which is needed by the view) How do I serialize just the created account object with the created token string into one response? This is my serializer (simplified and stripped from some stuff, but that's basically it) class UserRegistrationSerializer(serializers.Serializer): email = serializers.EmailField(write_only=True) # some other fields password = serializers.CharField(style={'input_type': 'password'}, write_only=True, validators=settings.get('PASSWORD_VALIDATORS') ) # this should be the output account = Account(read_only=True) def save(self): … -
how to add social authentication (Facebook) in django==1.8.6
I would like to add a social authentication Facebook. i have installed python-social-auth==0.2.12. made changes in settings.py. migrated. but when i runserver and wanted to authenticate wit facebook i have a mistake " ca not load URL. domain of this URL is not included in app domains." but I have included the domains tooo -
Extra row on Bootstrap navigation bar
My navigation bar is added an extra row and I have no idea why. My navigation bar has two sides: left and right. Left side contains 3 labels, one of them is a dropdown menu. The right side has two labels and the first label always adds another row. Here is my code, I'm using Django + Bootstrap 3.3.7, jquery 1.12.0. <div class="navbar-collapse collapse" id="topNavBar"> <ul class="nav navbar-nav"> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <span class="caret"></span>&nbsp Looking for... </a> <ul class="dropdown-menu"> <li class=""> <a href="{% url 'service:room' %}"> <span class="glyphicon glyphicon-bed" aria-hidden="true"></span>&nbsp Rooms </a> </li> <li class=""> <a href="{% url 'service:book' %}"> <span class="glyphicon glyphicon-book" aria-hidden="true"></span>&nbsp Textbooks </a> </li> <li class=""> <a href="{% url 'service:restaurant' %}"> <span class="glyphicon glyphicon-cutlery" aria-hidden="true"></span>&nbsp Restaurants </a> </li> <li class=""> <a href="{% url 'service:tutor' %}"> <span class="glyphicon glyphicon-education" aria-hidden="true"></span>&nbsp Tutoring </a> </li> </ul> </li> <li class=""> <a href="{% url 'service:result' %}"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span>&nbsp Searching <a> </li> </ul> <!-- </ul> --> <ul class="nav navbar-nav navbar-right"> {% block addbar %} {% endblock %} <!-- <li class=""> <a href="#"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>&nbsp Add Room </a> </li> --> {% if request.user.is_authenticated %} <!-- Link to user's profile --> <li class=""> <a href="{% url 'service:personal-rooms' %}"> <span … -
Am I doing it wrong or django rest api framework / coreapi has a bug ?
I'm experiencing some troubles about the coreapi and django rest api, perhaps someone can help me to understand what is wrong. The point is that on update and partitial_update the schema is returns the same fields twence: "update": { "_type": "link", "url": "/lindex/puddle/{name}/", "action": "put", "encoding": "application/json", "fields": [ { "name": "name", <-- Here "required": true, "location": "path", "schema": { "_type": "string", "description": "A unique value identifying this puddle.", "title": "name" } }, { "name": "name", <-- Here "required": true, "location": "form", "schema": { "_type": "string", "description": "", "title": "Name" } }, When coreapi does this call create = client.action(schema, ['api', 'v1', 'puddleatom', 'update'], { "name": "1NEW", #"names": "RAW_TR_BOS_CDR_201701-NEW", "ingestion_flow": "ING-RAW_TR_BOS_CDR", "status": "OK", "location": "hdfs://hdfs-prod/user/hive/warehouse/repl_jmailer_tr.db/bos_cdr_201701", "comment": "This atom contains data about BOS_CDR in 201701", "records": 29452695, "size": 2022540894, "files": 10, "puddle": "RAW_TR_BOS_CDR" }) the url computed is wrong: http://172.17.0.2:8000/api/v1/puddleatom/{name}/ This happens because the function _get_params into /usr/local/lib/python2.7/dist-packages/coreapi/transports/http.py allocate the parameters into the form and not into the path key[status], value[OK] location:form key[comment], value[This atom contains data about BOS_CDR in 201701] location:form ------------------- name is printed just once and the destinatation is form key[name], value[1NEW] location:form -------------------- key[records], value[29452695] location:form key[puddle], value[RAW_TR_BOS_CDR] location:form key[ingestion_flow], value[ING-RAW_TR_BOS_CDR] location:form key[files], value[10] location:form key[size], value[2022540894] … -
forms which can apply conditions for individual fields in django
I need a form with html created fields with values of a model. I've created one with generic view concept.But in one field of drop down list I don't want to display the items with the Boolean available is false.In generic view concept I am unable to give the condition for a single field.How can I do this. -
Writable nested serializers User and User profile doesn't work
I'm trying to create a user registration endpoint through django rest framework with his profile and it shows me that I have not created an explicit .create() method for my serializer. What I'm missing? here's my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) language = models.CharField(max_length=4, default='es') def __unicode__(self): return "%s - %s" % (self.user, self.language) my serializers.py class ProfileCreateSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = [ 'language', ] class UserSerializer(serializers.ModelSerializer): profile = ProfileCreateSerializer() class Meta: model = User fields = [ 'username', 'profile', ] def create (self, validated_data): user = User.objects.create(username=validated_data['username']) user.set_password(User.objects.make_random_password()) profile_data = validated_data.pop('profile') Profile.objects.create(user=user, **profile_data) user.save() My views.py class ProfileCreateAPIView(CreateAPIView): queryset = User.objects.all() model = Profile serializer_class = UserSerializer -
Django 1.10 How to display a field two different ways in Admin
I installed django-tinymce and used its HTMLField for one of my models, which was previously a TextField. In Django Admin, currently I have the field displayed as an HTMLField and can edit it using tinymce. However, I also want to display the same field as a TextField in admin to be able to have more control over the HTML of the field. -
How to refer a column that matches a foreign key in another table in Django?
I am very new to Django. I run into a problem where I need to refer a column that is neither a primary key nor unique value from another table. Here is my code: class Assignment(models.Model): assignment_id = models.CharField(primary_key=True, max_length=11) investor_id = models.ForeignKey('Investor', to_field='investor_id', models.DO_NOTHING) issuer_id = models.ForeignKey('Issuer', to_field='issuer_id', models.DO_NOTHING) investor_risk_attitude = models.ForeignKey('Investor', to_field='investor_risk_attitude', models.Do_NOTHING) interest_rate = models.FloatField(blank=True, null=True) tranche = models.CharField(max_length=20, blank=True, null=True) def get_absolute_url(self): return reverse ('assignment:index') class Meta: managed = False db_table = 'assignment' def __str__(self): return self.assignment_id class Investor(models.Model): investor_id = models.CharField(primary_key=True, max_length=11) investor_name = models.CharField(max_length=45, blank=True, null=True) investor_risk_attitude = models.CharField(max_length=45, blank=True, null=True,db_index=True) def get_absolute_url(self): return reverse ('investor:index') class Meta: managed = False db_table = 'investor' def __str__(self): return self.investor_id class Issuer(models.Model): issuer_id = models.CharField(primary_key=True, max_length=11) issuer_name = models.CharField(max_length=45, blank=True, null=True) issuer_category = models.CharField(max_length=45, blank=True, null=True) total_pool_amount = models.FloatField(blank=True, null=True) login_id = models.CharField(max_length=45, blank=True, null=True) login_password = models.CharField(max_length=45, blank=True, null=True) class Meta: managed = False db_table = 'issuer' def __str__(self): return self.issuer_id In Assignment table, I need to refer investor_risk_attitude from the Investor table, which I have made an index, but it is not a unique value. Because investor_id is also a foreign key in Assignment table, so I need the risk_attitude to match with its … -
Use Celery or Pika for Text Messages in Django / Rabbitmq environment?
Celery and Pika both utilize rabbitmq. I'm making a django app that does text messaging in an asyncronous environment. My inner developer says "Try to use Celery for both, since it uses rabbitmq." But another voice says " Use Pika along with Celery for their particular strengths -- celery for the multitasking, and pika for messaging. I'm a perfectionist -- Does celery do straight-up messaging like Pika does? Or should should I use Pika and Celery, both communicating with Rabbitmq? I have done extensive research, and for some reason I cannot find an example of using Celery to send text messages. Any guidance on this would be appreciated. This is not an opinion question - this is to find out if using Celery for text messaging is stupid. -
Unable to run Scrapy code
I have written the following coding to scrape the data from a website: spiders.settings.py code: import os import sys import django DJANGO_PROJECT_PATH = '/home/priyanka/myproject' DJANGO_SETTINGS_MODULE = 'myproject.settings' sys.path.insert(0, DJANGO_PROJECT_PATH) os.environ['DJANGO_SETTINGS_MODULE'] = DJANGO_SETTINGS_MODULE django.setup() BOT_NAME = 'scraper' SPIDER_MODULES = ['scraper.spiders'] NEWSPIDER_MODULE = 'scraper.spiders' example.py file in spiders folder code: from scrapy.spiders import BaseSpider from scraper.items import WebScraperItem class ExampleSpider(BaseSpider): name = ["timeandzone"] allowed_domains = ["timeandzone.com"] start_urls = ['http://timeandzone.com/worldclock'] def parse(self, repsonse): title = response.xpath('/html/body/div[1]/div[8]/section[2]/div[1]/table/tbody').extract() return WebScraperItem(title=title) I'm getting the following error on running the command "scrapy crawl ExampleSpider": Traceback (most recent call last): File "/usr/bin/scrapy", line 9, in <module> load_entry_point('Scrapy==1.0.3', 'console_scripts', 'scrapy')() File "/usr/lib/python2.7/dist-packages/scrapy/cmdline.py", line 142, in execute cmd.crawler_process = CrawlerProcess(settings) File "/usr/lib/python2.7/dist-packages/scrapy/crawler.py", line 209, in __init__ super(CrawlerProcess, self).__init__(settings) File "/usr/lib/python2.7/dist-packages/scrapy/crawler.py", line 115, in __init__ self.spider_loader = _get_spider_loader(settings) File "/usr/lib/python2.7/dist-packages/scrapy/crawler.py", line 296, in _get_spider_loader return loader_cls.from_settings(settings.frozencopy()) File "/usr/lib/python2.7/dist-packages/scrapy/spiderloader.py", line 30, in from_settings return cls(settings) File "/usr/lib/python2.7/dist-packages/scrapy/spiderloader.py", line 22, in __init__ self._load_spiders(module) File "/usr/lib/python2.7/dist-packages/scrapy/spiderloader.py", line 26, in _load_spiders self._spiders[spcls.name] = spcls TypeError: unhashable type: 'list' -
How to make Django The redirects app higher than urls.py?
Right now i'm using Django The redirects app, but it has some problem. I can't redirect from url, that have pattern in urls.py For example i can't redirect from /arsenal1 to any page, because pattern handle it before redirect app. url(r'^arsenal(?P<arsenal_id>[0-9]+)$', views.arsenal, name='arsenal'), So, how can i make the high priority to The redirects app? -
Can a database connection leak cause increased CPU usage?
There's a server that might be experiencing PostgreSQL database connection leaks. That server has also maxed out it's CPU at times (as indicated by %user being extremely high upon running sar -u). Could database connection leaks be causing the abnormally high CPU usage? -
DLL load failed: The operating system cannot run %1
Running Python 2.7.10 with Django 1.8.2 Apache 2.2 is running this. With Forms, I connecting to sftp server via paramiko to validate a file is present before submitting. If the directory or file is not present it raise forms.ValidationError This all works with manage runserver 0.0.0.0:80 but when I turn on apache, I receive this: Request Method: POST Request URL: http://localhost/submission/ Django Version: 1.8.2 Exception Type: ImportError Exception Value: DLL load failed: The operating system cannot run %1. Exception Location: C:\Python27\lib\site-packages\paramiko\transport.py in start_client, line 500 Python Executable: C:\Apache2\bin\httpd.exe Python Version: 2.7.10 def verifyftp(path): transport = paramiko.Transport((host, port)) transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) ret = 0 if '\\' in path: path = path.replace('\\','/') if host in path: path = path.replace(host + '/', '') out = re.search('(.*)/(.*)',path) try: dirt = sftp.listdir(out.group(1)) except: ret = -1 if ret != -1: if not out.group(2) in dirt: ret = -2 sftp.close() transport.close() return ret -
Django: Model query extract not looping in template
So, I'm making this app in django and using this code: My template tag in video_select.py file: @register.assignment_tag def content_list(): contentlist = vvideo.objects.all() return contentlist My template: {% load video_select %} <article id="menu" style="height:80%;"> <h2 class="major">Menu</h2> <div> {% for contentt in content_list %} {{ contentt.video_path }} {% endfor %} </div> <h2 class="major">End Menu</h2> </article> This displays nothing. But I'm not sure why. Conversely, simply printing out {% content_list %} does print out this output: [<vvideo: vvideo object>, <vvideo: vvideo object>, <vvideo: vvideo object>, <vvideo: vvideo object>, <vvideo: vvideo object>, <vvideo: vvideo object>] So clearly the template tag is working. My models.py contains: class vvideo(models.Model): video_path = models.CharField(max_length=200, blank=True, null=True) so, clearly the .video_path reference is also correct. Can you help me understand why my list isn't looping & printing out? I tried iterating it directly in the template tag and it is working. However, I really want the loop to run in the template itself because I am trying to create href links for each video. So, I need to loop through all videos in the database and extract their names and urls, creating respective links. That's two items required for each line output: therefore, it's probably better to send … -
json_response_message() got multiple values for keyword argument 'response' - django
I am getting this error json_response_message() got multiple values for keyword argument 'response' I figured how I get this error though but I just cannot find out a workaround for this, is there anyone able to give me a hand? the reason for this error is because of this line return json_response_message(success_response(), response=response) these are the two functions I created and they work fine though, def json_response_message(response, **kwargs): data = {} print(response) print(kwargs) data.update(response) data.update(kwargs) return JsonResponse(data) def success_response(*args): # initial message to ok message = 'OK' # if there is *args then add this to the message if args: for value in args: message += value return { 'status': True, 'code': 200, 'message': message } I figured if I do something like this, everything would work fine return json_response_message(success_response(), change_this=response) is it because response is a reserved word or something? either way, is there a way I can still make it happen to be response=response ? Because all the structure in front end has already been set up. I don't really want to change anything if I don't have to as long as I have some workaround on my side. Can someone please give me a hand? Thanks in … -
Django can load image from static files but not using css
I don't understand why my static files (css and images) are properly loaded in my Django project, it works fine when I load the static file from an html tag but when I want to set a background image through css background: url('images/mypic.png') (I also tried url('../images/mypic.png')) andit doesn't work at all. The image is loaded in the img tag but not in the divs where I call the css {% load static staticfiles cms_tags menu_tags sekizai_tags %} <!doctype html> <html> <head> <title>{% block title %}This is my new project home page{% endblock title %}</title> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="{% static 'css/styles.css' %}"/> {% render_block "css" %} </head> <body> {% cms_toolbar %} <div class="container"> <header> <nav> <div class="nav_logo"></div> <ul class="nav"> {% show_menu 0 100 100 100 %} </ul> </nav> </header> <main class="container"> <img src="{% static 'images/logo_aasev.png' %}" alt="Photo de montagne" /> <div style="background-image: url('{% static "images/logo_aasev.png" %}')"></div> {% block content %}{% endblock content %} </main> <footer> </footer> </div> {% render_block "js" %} </body> </html> and my css: * { margin: 0; padding: 0; } header { width: 100%; background-color: #000; } nav { width: 90%; margin: 0 auto; padding: 10px 0px; } .nav { padding-left: 0; } .nav li … -
Protection From Browser Dev Tools Changing POST Values
After looking around for a bit, I cannot seem to find an answer to my question... Or maybe I am just not wording my question correctly in my search. Any-who, my question and description is as follows: I am building a web application using Django, Javascript, HTML, and all that Jazz. I am currently testing my checkout page and noticed a security issue I do not know how to handle. Issue: I can open up developer tools and change the 'value' of whatever I want on my HTML and that is the value that ultimately gets passed back in the POST request. How do I make it so that changing the HTML values using dev tools on the browser doesn't effect the values being sent back? -
SSL: TLSV1_ALERT_INTERNAL_ERROR when connecting to APNS
My servers APNS notifications recently stopped working and after debugging I found that the SSL python library is throwing the following error when opening a socket: File "/home/tam/repos/rest/api/tasks/notification_tasks.py", line 17, in apns_socket self._apns_socket = apns.open_apns_socket() File "/home/tam/repos/rest/api/utilities/apns.py", line 64, in open_apns_socket return _apns_create_socket((settings.APNS_HOST, settings.APNS_PORT)) File "/home/tam/repos/rest/api/utilities/apns.py", line 49, in _apns_create_socket sock.connect(address_tuple) File "/usr/lib64/python3.5/ssl.py", line 1014, in connect self._real_connect(addr, False) File "/usr/lib64/python3.5/ssl.py", line 1005, in _real_connect self.do_handshake() File "/usr/lib64/python3.5/ssl.py", line 983, in do_handshake self._sslobj.do_handshake() File "/usr/lib64/python3.5/ssl.py", line 628, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: TLSV1_ALERT_INTERNAL_ERROR] tlsv1 alert internal error (_ssl.c:645) Nothing has changed on the server codewise. I've checked APNS certificates (they haven't expired), and our SSL certificate (also not expired). I'm unsure what else could be causing this error at this point. Here are the relavent lines of code from apns.py: def open_apns_socket(): return _apns_create_socket((settings.APNS_HOST, settings.APNS_PORT)) def _apns_create_socket(address_tuple, is_dev=False): certfile = settings.APS_CERTIFICATE if not certfile: raise ImproperlyConfigured('You need to set settings.APNS_CERTIFICATE') try: with open(certfile, "r") as f: f.read() except Exception as e: raise ImproperlyConfigured("The APNS certificate file at %r is not readable: %s" % (certfile, e)) ca_certs = settings.APNS_CA_CERTIFICATES sock = socket.socket() sock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_TLSv1, certfile=certfile, ca_certs=ca_certs) sock.connect(address_tuple) return sock -
Django Fullcalendar ajax no showing events
Hi I can't get events from ajax call to calendar please help template: $('#calendar').fullCalendar({ ..... events:{ url:'{% url 'rezerwacje' %}', type: 'GET', }, url.py url(r'^rezerwacje/json2/', views.RezerwacjeLista, name='rezerwacje'), views.py def RezerwacjeLista(request): if request.is_ajax(): try: start = request.GET.get('start', False) print start end = request.GET.get('end',False) except ValueError: start = datetime.now() end = start + timedelta(days=7) rezerwacje = Rezerwacje.objects.filter(start__gte=start).filter(end__lte=end) json_list = [] lista = [] for rezerwacja in rezerwacje: id = rezerwacja.id start = rezerwacja.start.strftime("%Y-%m-%d %H:%M:%S") stanowisko = rezerwacja.stanowisko.nazwa end = rezerwacja.end.strftime("%Y-%m-%d %H:%M:%S") kolor = rezerwacja.kolor status = rezerwacja.status #allDay = False json_entry = {"id":'1', 'start':start, 'end':end,'resourceId':stanowisko, 'kolor':kolor, 'status': status} json_list.append(json_entry) lista = ast.literal_eval(json.dumps(json_list)) return HttpResponse(lista, content_type='application/json') That view returns json: {'kolor': '1', 'status': 1, 'end': '2017-05-03 15:00:00', 'resourceId': 'K1', 'start': '2017-05-03 14:00:00', 'id': '1'} That is good but when i select date in calendar there is no result on events. In response i get url and json http://127.0.0.1:8000/rezerwacje/json2/?start=2017-05-03&end=2017-05-04&_=1493937740198 How to pass result to ajax?