Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error statement on Django and Python web development
I've one problem here on elif statement. The process is taking the value from check box selected by the user and compare it to a statement. Checkbox id/name call token, which has two value visual and time. The user can check either visual or time and pass to views.py using a token variable. THIS views.py context = {} data = {} prev_key = '' with open(path) as input_data: for line in input_data: if (token == 'visual'): if line.startswith('2_visualid_') prev_key = line.lstrip('2_visualid_').rstrip() data.update({line.lstrip('2_visualid_').rstrip(): []}) elif (token == 'time'): if search_string in line if prev_key in data: data[prev_key].append (next(input_data).lstrip('2_mrslt_').rstrip()) context = {'output': data} return render(request, 'Output.html', context) When I select Visual in my check box is working. But comes to only select time is not working. If I choose both also it displays nothing in my table. This my checkbox html <form action=""> &nbsp&nbsp<input class="regular-checkbox" type="checkbox" name="token" value="visual"><b>&nbsp&nbsp Visual ID</b><br> &nbsp&nbsp<input class="regular-checkbox" type="checkbox" name="token" value="time"><b>&nbsp&nbsp Time Delay Index</b> </form> This is tabular HTML output <div class="input-group" align="center" style=" left:10px; top:-110px; width:99%"> <table class="table table-bordered"> <thead class="success" > <tr> <th class="success"> <b>Visual ID</b> </th> <th class="success"> <b>Time Delay Index Time</b> </th> </tr> {% for key, values in output.items %} <tr class="warning"> <td rowspan={{ … -
DataError exception instead of form validation error - max_length
bill_to2 model field max_length is 20. When I try to send my form with value lenght more than 20 I get: value too long for type character varying(20) / Exception Type: DataError instead of form validation error. What is the reason? class InviteCandidateForm(forms.Form): def __init__(self, user, *args, **kwargs): super(InviteCandidateForm, self).__init__(*args, **kwargs) self.user = user if self.user.company.display_bill_to2: self.fields['bill_to2'] = forms.CharField() self.fields['bill_to2'].label = self.user.company.bill_to2_label self.fields['bill_to2'].required = True self.helper = FormHelper() self.helper.form_method = 'post' self.helper.layout = Layout( Fieldset( '', 'name', 'email', 'bill_to2', ), ButtonHolder( Submit('save', 'Send', css_class='button') ) ) name = forms.CharField() email = forms.EmailField() -
django visualization and dashboard graph build
i want to build a simple analysis application by using django framework , what's the best lib,module for designing UI that represent graphs and let me display my visualization output. -
cities, country and zip_code models fields and modelsforms with django-cities
I'm trying to make three models fields cities, country and zip_code in my model so I can build a ModelForm and setup some custom signup, and for that I'm using dajngo-cities library. I've configured everything I need for the app in my project and I've done the migrations, so I have loaded US cities, countries and zip_codes in the system, but now I'm failing to understand how can I build this model fields so I can make dropdown select buttons in my forms, can someone please explain me how to build this properly, thanks. -
Django web, Pycharm
enter image description here enter image description here I installed PyCharm version number is 2017.2.2 64bit. But PyCharm problem came out. The prompt is "C:\Program Files\JetBrains\PyCharm 2017.2.2\bin\ runnerw.exe" C:\Windows\System32\django_basic_venv\Scripts\python.exe D: /workspace/hongmingxing/5web/hello_django/manage.py Runserver 8000 CreateProcess failed with error 2: I can not find the specified file. But windows 10 inside the cmd is normal operation, but PyCharm on error, how to solve? please? -
Is there any way to save success message in context in django
I created a model form.Is it possible to add some message in context in views.py ? Actually i want to display a success message in template page when form is submitted and data added in database. for example i want to do this: if form.save: msg = 'Data inserted successfully' context = {'msg': msg,} I want to save success message in my context so therefore i will show in my template page -
object stops being draggable
I'm trying to setup a dashboard that lets some users manage the permissions of other users. I want to do this via a drag and drop interface. I tried to implement this and got to a point where almost everything seemed to work, except the divs being dragged around stopped being draggable after they were drag and dropped the first time. Searching around I saw people suggesting I had to add the following to my js, $('div#' + id).draggable({ helper: 'clone' }) When I do that however I end up with two copies of the div, one snaps to place as dictated by the class='box' css, one exactly at the spot where I dropped the object, and neither is draggable. The html code (wrapper is a flex-box container): <div id="wrapper"> <p>group1</p> <div class = "box" id="group1"> {% for user in group1 %} <div id='{{ user.email }}' class="button-dashboard button-bright">{{ user.name }}</div> {% endfor %} </div> <p>group2</p> <div class = "box" id="group2"> {% for user in group2 %} <div id='{{ user.email }}' class="button-dashboard button-bright">{{ user.name }}</div> {% endfor %} </div> </div> My js: $(document).ready(function () { $('.box div').draggable({ helper: 'clone' }); $('.box').droppable({ drop: function(event, ui){ var id = $(ui.draggable).attr('id'); var user = … -
Django SESSION_COOKIE_HTTPONLY set but the HttpOnly flag does not show up on cookies
I've set this variable in the settings file like this: SESSION_COOKIE_HTTPONLY = True but when I open the website with Google Chrome HttpOnly does not show up in set-cookie. My webserver is Apache2.4, and the website is using Https protocol. -
Issue sending json request in django
i am working on a project and i want to encorporate SynapseFi api call into my django project. Looking at their documentation, they ask for a few parameters which I have add into a django function/method that is called to send a request to eh api and receive a response. I am not sure where, but i can not get it to work and i have been working on figuring this out for a few days. Maybe someone here can help.. I will add the documentation portion and what i have so far... Documentation The following is going to be added to the header of the request... POST /v3.1/users HTTP/1.1 Host: uat-api.synapsefi.com X-SP-GATEWAY: client_id_2bb1e412edd311e6bd04e285d6015267|client_secret_2bb1e714edd311e6bd04e285d6015267 X-SP-USER-IP: 127.0.0.1 X-SP-USER: |e83cf6ddcf778e37bfe3d48fc78a6502062fc Content-Type: application/json And this is a sample object that is going to be passed with the response... { "logins": [ { "email": "test@synapsepay.com" } ], "phone_numbers": [ "901.111.1111", "test@synapsepay.com" ], "legal_names": [ "Test User" ], "extra": { "supp_id": "122eddfgbeafrfvbbb", "cip_tag":1, "is_business": false } } * My Code * this is what I have in a function that will be called from a method.... the headers goes into the request headers with the main url and the payload. Is there a way to … -
how to use python Django and Spark
I am going to start a mock web application development with Python Django, and I would want to use Spark as an integration with my web app. Is it even possible? if yes, how? We can bring data from database to Spark through sparkContext coding, but is there a way to directly integrate my web app to Spark? -
making urls for django and gitlab CI
I have a droplet in Digitalocean where I installed gitlab CI The problem is that every domain I create it redirects to gitlab page How can I make only 1 url that takes to gitlab ci and one for django? -
How to curl in django like php
I want to send image to my telegram channel with my telegram bot. I know how to curl image with PHP, but i can't curl it with Django. Here is php way : $bot_url = "https://api.telegram.org/botxxxxxxxxxxxxxxxxxx/"; $chat_id = "@mychannel"; $url = $bot_url . "sendPhoto?chat_id=" . $chat_id ; $post_fields = array('chat_id' => $chat_id, 'photo' => new CURLFile(realpath("1.jpg")) ); $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Content-Type:multipart/form-data" )); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); $output = curl_exec($ch); I want to curl it in Django. Note : my Django version is 1.10 -
DRF - Extending User model to Profile model and create Profile
Well, basically I want to extend my django User model to a Profile model, which will reference the User model using a OnetoOneField. I would need a proper writable DRF serializer for this, and the appropriate way to handle the serializer in a view (preferably a class/function-based view and NOT a viewset). I have referenced through a lot of posts but couldn't get any proper working method. Currently I am working with my Profile method referencing User method with a ForeignKeyField. Well, its not what I was looking for but it works for now. I am posting my current code, but I want to do it using OnetoOneField. Also, do I need to use any receiver or something like in simpleisbetterthancomplex.com blog? I tried to use receivers with my OnetoOne implementation, but failed miserably. models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) uid = models.CharField(max_length=64, unique=False, blank=False, null=False) def __str__(self): return self.user.username class Meta: db_table = 'profile' serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = [ 'id', 'username', 'email', 'password', 'first_name', 'last_name' ] class ProfileCreateSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), write_only=True) class Meta: model = Profile fields = [ 'user', 'uid', ] views.py class UserProfileCreate(APIView): def post(self, request, format=None): user_serializer = … -
How to approach a app constantly using 100,000+ data sources within mysql every ten seconds
I am trying to implement a app that fetches 100,000+ data leads, than searches the Internet constantly refreshing the data stored within mysql making decisions in real-time from the data in mysql. the app is fetching the data throughout the Internet and storing it within a database. After a set time limit logic occurs refreshing the mysql data set by titles. The reason I am on Stackoverflow asking the following question, how I approach further dev of the project is because maybe someone else has a better idea on how me or someone else trying to do the same project should approach creating an app like I am doing. Should I approach it like, set models. Create a script to fetch the data from the Internet, store the data received from the Internet to a database. Than logic fetching the data throughout the Internet from the data displayed with specific titles within the db. After, another logic script seeing if the data has been updated within a ten second time span. All being processed by a central decision script. It's essentially an AI using Python, Django, MySQL and few other open source libraries. My question is about how I should … -
How to integrate code coverage with Django test tags
Anyone have any advice on or projects that help with integrating Django's test tags with coverage.py or another coverage tool so you can see code coverage by tag? -
Create 2 endpoints or methods based on the same model - django restframework
Trying django rest framework, is possible to have 2 endpoints returning different data based on the same model? I need something like this. api/tarjetas should return all the objects created while api/tarjetasusuario should return objects created by an specific user. Thanks class TarjetaViewSet(viewsets.ModelViewSet): queryset = Tarjeta.objects.all() serializer_class = TarjetaSerializer permission_classes = (OwnerPermission,) class TarjetasusuarioViewSet(APIView): queryset = Tarjeta.objects.all() serializer_class = TarjetaSerializer permission_classes = (OwnerPermission,) def get_queryset(self): return Tarjeta.objects.filter(usuario=self.request.user) -
InvalidBaseError when trying to convert Parent Model to an Abstract Parent model
I have been at this problem for days, and just can't figure out. Maybe someone more knowledgable with Django can point me in the right direction. Any help appreciated! I have this parent model: class ReservedSlug(models.Model): slug = models.SlugField( max_length=80, unique=True, ) And I also have to classes that Reference it: class ChildClass1(ReservedSlug): and class ChildClass2(ReservedSlug): Now I would like to remove this dependency overall, and I think to do that, I need to start out by making the ReservedSlug Class to abstract =True And in my migrations file I create the field on each Child Class that the parent class had: operations = [ migrations.RemoveField( model_name='ChildClass1', name='reservedslug_ptr', ), migrations.RemoveField( model_name='ChildClass2', name='reservedslug_ptr', ), migrations.AddField( model_name='ChildClass1', name='id', field=models.AutoField(auto_created=True, default=0, primary_key=True, serialize=False, verbose_name='ID'), preserve_default=False, ), migrations.AddField( model_name='ChildClass1', name='slug', field=models.SlugField(default='test', max_length=80, unique=True), preserve_default=False, ), migrations.AddField( model_name='ChildClass2', name='id', field=models.AutoField(auto_created=True, default=0, primary_key=True, serialize=False, verbose_name='ID'), preserve_default=False, ), migrations.AddField( model_name='ChildClass2', name='slug', field=models.SlugField(default='test', max_length=80, unique=True), preserve_default=False, ), ] However, when I try to migrate I get the following error: InvalidBasesError: Cannot resolve bases for [ModelState: 'company.Industry', ModelState: 'company.Company'] And I just cannot get my head around to what to do! Again, my goal is to fully decouple the ChildClass1 and ChildClass2 from ReserveSlug. Before the above migration, I … -
Django & psycopg2: FATAL: password authentication failed for user
I'm having trouble connecting to my postgres database from my django site. Before beginning, I have read and attempted the instructions provided at each of these sites: Django setting : psycopg2.OperationalError: FATAL: Peer authentication failed for user "indivo" OperationalError: (psycopg2.OperationalError) FATAL: password authentication failed for user FATAL: password authentication failed for user "root" postgresql postgresql: FATAL: password authentication failed for user "douglas" Any assistance you are able to provide with the problem described below would be most-helpful in completing this site for a non-profit. Thank you in advance. Traceback Traceback is too large for this post. See: https://pastebin.com/fX7NY36M. uname kris@dask:~$ uname -a Linux dask 4.9.36-x86_64-linode85 #1 SMP Thu Jul 6 15:31:23 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux pg_hba.conf kris@dask:~$ sudo cat /etc/postgresql/9.5/main/pg_hba.conf ... local all postgres peer # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all md5 # IPv4 local connections: host all all 127.0.0.1/32 md5 # IPv6 local connections: host all all ::1/128 md5 # Allow replication connections from localhost, by a user with the # replication privilege. #local replication postgres peer #host replication postgres 127.0.0.1/32 md5 #host replication postgres ::1/128 md5 wsgi.py kris@dask:/home/dask/www/code/daskretreats_org$ cat wsgi.py """ WSGI config for … -
Several AngularJS controllers do not working in DjangoTemplates, the value is not transferred
I expect <script>console.log("{{ test_text }}");</script> to return "hello world" when the view is accessed, but it returns "". The {{ buttons|length }} also returns "0" where I am expecting it to return "3". I have another controller in navbar.js that I put just before </body>. The one controller I put in navbar.js is working. The values are still not transfered if I put the codes from template_1.js into navbar.js. Additionally, I have made sure that both controllers from template_1.js and navbar.jshave the correct syntax, but with different contents. I am using DjangoTemplates, if it does anything related to this problem. Here are my codes. template_1.html {% load static %} <div id="pagination-main"> <!-- If a user is logged in show the management panel for the shop manager --> {% if user.is_authenticated and not user.is_superuser %} <div id="cashier-management-panel" ng-controller="cashier_management_panel"> <script>console.log("{{ test_text }}");</script> <div class="cashier-management-title">cashier informations</div> <div class="cashier-management-button-container" ng-repeat="button in buttons"> <button class="btn btn-block cashier-management-button {{ button.bootstrap_color }}"> {{ button.text }} </button> </div> </div> {% endif %} </div> template_1.js app.controller("cashier_management_panel", function ($scope) { $scope.buttons = [ { "bootstrap_color": "btn-success", "text": "submit" }, { "bootstrap_color": "btn-warning", "text": "go to <br /> current cashier" }, { "bootstrap_color": "btn-primary", "text": "go to <br /> current cashier" … -
Positioning in Django Template by Models Field
Hello i want to put my players in html according to their positions from my model like if one players position field is added as "striker" in model i want to put them in div with "Strikers" class. How can i do that? here is my models.py class Player(models.Model): position = models.CharField(max_length=120, verbose_name="Position") player_name = models.CharField(max_length=120, verbose_name="Player") player_age = models.IntegerField(null=True, blank=True, verbose_name="Player Age") And here is my html; <div class="Strikers"></div> <div class="Midfielders"></div> And here is my views.py; def player_index(request): players = Player.objects.all() return render(request, "players/index.html", {'players': players}) Thanks so much in advance.. -
django admin how to get new object's id when overriding save_related
I have the code below where I have modified the admin form to pass additional info which is then used after the save process is done. This works fine when using the save button. The problem with the code below is that when someone uses the "save as new" button, sample_pk would be the id of the current sample not the new sample that is generated. My question is how to get the new object's id after calling the super on save_related. @admin.register(Sample) class SampleAdmin(ModelAdmin): save_as = True def save_related(self, request, form, formsets, change): super(SampleAdmin, self).save_related(request, form, formsets, change) args = request.resolver_match.args if len(args) < 1: # not previously saved return sample_pk = int(args[0]) new_things = [] for formset in formsets: for key, val in formset.data.items(): if key.startswith('robo_'): new_things.append(val) x = sum(new_things) sam = Sample.objects.get(pk=sample_pk) OtherTable.objects.create(x=x, sample=sam) -
Complex Python Regex for Django View
URL structure look liks this: <domain>/<version>/<collection>/<sub-collection>/<page> where domain is anything a-zA-Z0-9\-\_, version is anything a-zA-Z0-9\-\_\. (But would likely be only 1.0, 1.1, 2.0.0 etc) and both collection and sub-collection are optional groups which follow restraints. Current regex is: r'^(?P<domain_slug>[a-zA-Z0-9\-\_]*)\/(?P<version_slug>[a-zA-Z0-9\-\_\.]*)\/(?P<slug>[a-zA-Z0-9\-\_]+)\/$. How can I capture optional positions, ensuring the last segment is always the page? Additionally, is this even a good idea? Would it be better to just pass this through the Django URL conf and let a view function handle all the work? Example URLs could include: administration/5.0.3/reset-user-password user/1.0/getting-started/setting-up-an-account development/3.2/authentication/acl/creating-aco -
Django can't connect to mysql via docker-compose
I have an application using Django and MySQL. The application does not connect to MySQL container from the Django Application but it can be accessed using Sequel Pro with the same credentials. This is my docker-compose.yml version: '2' services: db: image: mysql:5.7.18 ports: - "3307:3306" volumes: - "./mysql:/var/lib/mysql" command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci environment: - MYSQL_ROOT_PASSWORD=pass - MYSQL_DATABASE=django - MYSQL_USER=django - MYSQL_PASSWORD=pass web: build: context: . depends_on: - db # links: # - db volumes: - "./app:/src" command: bash -c "sleep 3 && python3 src/manage.py runserver 8000" ports: - "8001:8000" environment: - DJANGO_SETTINGS_MODULE=app.production - DB_NAME=django - DB_USER=django - DB_PASS=pass - DB_HOST=db - DB_PORT=3306 This is my django settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.getenv('DB_NAME', 'django'), 'USER': os.getenv('DB_USER', 'django'), 'PASSWORD': os.getenv('DB_PASS', 'pass'), 'HOST': os.getenv('DB_HOST', 'db'), 'PORT': os.getenv('DB_PORT', '3306'), 'OPTIONS': { 'sql_mode': 'STRICT_TRANS_TABLES', } } } And this is error that I don't know how to fix this web_1 | Performing system checks... web_1 | web_1 | Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7efeb8563950> web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.5/dist- packages/django/db/backends/base/base.py", line 213, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.5/dist- packages/django/db/backends/base/base.py", line 189, in connect web_1 | self.connection = self.get_new_connection(conn_params) … -
django specific user content/data
first post on stackoverflow. Ive been reading/watching everything I can, but im still very new to this. Any help would be greatly appreciated Im trying to display specific content/data based on a logged in user. I want to display only their info. This is what ive tried but i cant get it to work. In views.py class DemoView(TemplateView): template_name = 'demographics/demographics.html' def get(self, request): demos = Demographics.objects.filter(user=request.user) context = { 'demos': demos, } return render(request, self.template_name, context) models.py class Demographics(models.Model): first_name = models.CharField(max_length=50, null=True) middle_name = models.CharField(max_length=50, null=True) last_name = models.CharField(max_length=50, null=True) user = models.ForeignKey(User, null=True) I feel like im close. what im a missing?? -
get foreign key from model
Hello I want to get fk from model model.py class Produit(models.Model): ref=models.CharField(max_length=100, default='',primary_key=True) marq=models.CharField(max_length=100, default='') nomp=models.CharField(max_length=100, default='') qte = models.IntegerField(default=0) codecateg=models.ForeignKey(categorie, on_delete=models.CASCADE) class categorie(models.Model): codecateg=models.CharField(max_length=100, default='' , primary_key=True) nomcat=models.CharField(max_length=30, default='' ) views.py def edit_prod(request , id = None): ins = get_object_or_404(Produit,ref=id) datedit = {'ins': ins} return render(request, 'produit/modal_prode.html',datedit ) when i want to get ins.codecateg i get categorie object