Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redirecting to a separate Django view after Ajax request is successful
Django/Python server-side dev here. And also a JS newbie (8 days old). This question is about Ajax-initiated page reloads. Here's a JS snippet where I'm processing the JSONResponse from a Django view I POSTed some data to. Depending on success or failure, you'll see that I'm calling a redirect to another Django view: var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var resp = JSON.parse(this.responseText); if (!resp.success) { console.log("Failed!"); } else { console.log("Success! Redirect to: ", resp.success_url); window.location.href = resp.success_url; window.location.reload(); } } }; xhr.open('POST', e.target.action); xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken')); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.send(form_data); Specifically, the following lines do the trick: window.location.href = resp.success_url; window.location.reload(); My problem is that when this gets executed in Firefox, I am made to see the following dialog box: It seems the POST parameters are being sent again ?! How do I just do a plain old GET type redirect to resp.success_url instead? Please advise and let me know if you need more information. Note: let's stick to pure JS for the scope of this question - I'm learning vanilla JS these days and don't want to get into JQuery prematurely. -
no display name and no $DISPLAY environment variable django and matplotlib
I have views.py like bellow: import matplotlib.pyplot as plt import matplotlib def anyfunction(request): a1=[i.created_date.strftime("%D") for i in model.objects.all()] b1=dict((x,a1.count(x)) for x in set(a1)) c1=sorted(d1.items(), key=lambda x: x[0]) c11=[i[0] for i in c1] c12=[i[1] for i in c1] matplotlib.use('Agg') fig = plt.figure() ax = fig.add_subplot(111) ax.plot(c11,c12) plt.bar(c11, c12, align='center') plt.title('Per Day User Visit Count') plt.ylabel('No of Per Day User Visit axis') plt.xlabel('Date ') fig.savefig('test.png') return render_to_response('sa.html') When i run it with django shell , its running fine , but when i put these codes in views.py , i am getting following error. no display name and no $DISPLAY environment variable Can i get some help here . -
Annotate queryset and display data in admin - Django
I'm new to both Django and Python. Currently I'm trying the Django Admin by doing. I've three models for a Django app, which are GoodsItem, SoldGoodsItem and FinishedGoodsItem. The models.py is: from django.db import models class GoodsItem(models.Model): name = models.CharField(max_length=255) size = models.DecimalField(max_digits=4, decimal_places=2) INCHES = 'IN' NUMBER = 'NUM' GOODS_ITEM_SIZE_UNITS = ( (INCHES, 'Inches'), (NUMBER, '#'), ) size_unit = models.CharField( max_length=4, choices=GOODS_ITEM_SIZE_UNITS, default=INCHES, ) def __str__(self): if(self.size_unit == self.NUMBER): return "%s #%s" % (self.name, (self.size).normalize()) else: return "%s %s\"" % (self.name, (self.size).normalize()) class FinishedGoodsItem(models.Model): date = models.DateField() goods_item = models.ForeignKey(GoodsItem, on_delete=models.CASCADE, related_name="finished_name") weight = models.DecimalField(max_digits=6, decimal_places=3) def __str__(self): return str(self.goods_item) class SoldGoodsItem(models.Model): goods_item = models.ForeignKey(GoodsItem, on_delete=models.CASCADE, related_name="sold_name") date = models.DateField() weight = models.DecimalField(max_digits=6, decimal_places=3) def __str__(self): return str(self.goods_item) And here is admin.py: from django.contrib import admin from django.db.models import Sum from .models import GoodsItem, FinishedGoodsItem, SoldGoodsItem @admin.register(SoldGoodsItem) @admin.register(FinishedGoodsItem) class FinishedGoodsItemAdmin(admin.ModelAdmin): fields = ('date', 'goods_item', 'weight') list_display = ('date', 'goods_item', 'weight') @admin.register(GoodsItem) class GoodsItemAdmin(admin.ModelAdmin): list_display = ('__str__', 'finished_good', 'sold_good', 'stock_available') def get_queryset(self, request): qs = super(GoodsItemAdmin, self).get_queryset(request) qs = qs.annotate( finished_good=Sum('finished_name__weight'), sold_good=Sum('sold_name__weight'), stock_available=Sum('finished_name__weight') - Sum('sold_name__weight'), ) return qs def finished_good(self, obj): return obj.finished_good def sold_good(self, obj): return obj.sold_good def stock_available(self, obj): return obj.stock_available In stock_available for each GoodsItem, I want … -
python 3.5 -> 3.6 Tablib TypeError: cell() missing 1 required positional argument: 'column'
Migrating from python 3.5 to 3.6, my unit tests reveal a problem with django-import-export & tablib: TypeError: cell() missing 1 required positional argument: 'column' File "<path>/lib/python3.6/site-packages/tablib/formats/_xlsx.py", line 122, in dset_sheet cell = ws.cell('%s%s' % (col_idx, row_number)) TypeError: cell() missing 1 required positional argument: 'column' The line in tablib: cell = ws.cell('%s%s' % (col_idx, row_number)) So indeed, there is no argument for the column My view code: my_resource = MyModelResource(queryset=my_queryset) dataset = my_resource.export() response = HttpResponse(dataset.xlsx, content_type='application/vnd.ms-excel') This works fine in python3.5 but fails under 3.6 requirements.txt: ... tablib==0.12.1 django-import-export==0.7.0 Django==1.11.7 ... -
Django template display first 3 related to that category
In reference to this model: My Model I want to show the first three items in one column / for loop, then another 3 in another column / for loop, e.g. Category 1 Item 1 Item 4 Item 2 Item 5 Item 3 Item 6 I tried using slices, but that only retrieves the first three in the object, so if the first two item belongs to Category 1, and the last item belongs to Category 2, it only show 2 items. I want to grab first 3 items for each category, then vice versa, last three items. -
Django Rest Framework Backend and Html/Javascript is Frontend call the url happened Uncaught SyntaxError: Unexpected identifier
$.ajax({ type:'GET' url:'http://127.0.0.1:8000/leave/requests/?format=json' success:function(data){ $.each(data, function(index, data){ var check_status = "Pending" if(data.approval_status == check_status){ if(username == data.reporter){ $('#waiting_for_approval').append (""+data.employee_name+""+ ""+data.from_date+""+ ""+data.to_date+""+ ""+data.no_days+""+ ""+data.leave_type_name+""+ ""+data.reason+""+ ""+data.approval_status+"" ) } } }); } }); }); -
Pycharm not recognizing package that shell does recognize. Django
I have installed a package, django_celery_beat. I can import it in the shell: >>import django_celery_beat >> But Pycharm shows me an error, it underlines the import as if the package wasn't installed. Why could this be? -
Can't get images to work in django
I'm getting a 404 error when trying to serve user uploaded files in local. I've tried a lot of suggestions from the forums but I can't get it to work. This is the error I can see on the logs. The image get uploaded properly to media/images but when I try to use that same image I get a 404 not found. I've tried to put the absolute path and didn't work either. Could anybody please help me? Thanks [03/Feb/2018 23:32:00] "GET /idealistos/30/ HTTP/1.1" 200 483 Not Found: /media/images/_D3L8637.jpg [03/Feb/2018 23:32:01] "GET /media/images/_D3L8637.jpg HTTP/1.1" 404 2239 settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] # Media files MEDIA_ROOT = 'media/' MEDIA_URL = '/media/' models.py from django.db import models from django.forms import ModelForm from django.utils import timezone from django.contrib.admin.widgets import AdminDateWidget # Create your models here. class Anuncio(models.Model): title = models.CharField(max_length=40) description = models.CharField(max_length=300) price = models.CharField(max_length=10) city = models.CharField(max_length=20) state = models.CharField(max_length=20) country = models.CharField(max_length=20) postcode = models.CharField(max_length=20) foto = models.FileField(null=True, blank=True, upload_to='images/') pub_date = models.DateTimeField(default=timezone.datetime.now()) def __str__(self): return self.title def __unicode__(self): return price class AnuncioForm(ModelForm): class Meta: model = Anuncio fields = ['title', 'description', 'price', 'city', 'state', 'country','postcode','foto'] views.py from django.http import Http404, … -
You don't have permission to access admin (Django, wsgi, Apache)
I want to configure my Debian server to provide my Django application. Everything is working fine but my Apache2 is blocking the access to my admin site. So when I am trying to access www.mydomain.com/admin the Apache2 says that I don't have permission to access that site. I can't get why. Alias /static /etc/website/portal/static Alias /media /etc/website/portal/static/media Alias /admin /etc/website/portal/static/admin <Directory /etc/website/portal/static/admin > Require all granted </Directory> <Directory /etc/website/portal/static> Require all granted </Directory> <Directory /etc/website/portal/static/media> Require all granted </Directory> <Directory /etc/website/portal/Portal> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess portal python-home=/etc/website/ python-path=/etc/website/portal WSGIProcessGroup portal WSGIScriptAlias / /etc/website/portal/Portal/wsgi.py The structure of my project on the server: -etc ---website 'that is my virtualenv' -----portal 'my project folder' -------manage.py -------templates -------Portal 'main project' -------SomeApp -------static ----------admin -------------'files of admin' ----------img ----------media ----------static I thought that I gave access with configuring following in the admin: Alias /admin /etc/website/portal/static/admin <Directory /etc/website/portal/static/admin > Require all granted </Directory> I also changed the permissions on the admin folder with chmod 777 and chown :www-data but it is still not working. I don't know if it is relevant but I use a MySQL database. Thank you for your help ! If some information are missing just let me know … -
ValueError at /accounts/upload_save/
I got an error,ValueError at /accounts/upload_save/ The view accounts.views.upload_save didn't return an HttpResponse object. It returned None instead. Always image cannot be sent normally. I wrote in views.py def photo(request): d = { 'photos': Post.objects.all(), } return render(request, 'registration/accounts/profile.html', d) def upload_save(request): if request.method == "POST": print(444) form = UserImageForm(request.POST, request.FILES) if form.is_valid(): print(5555) image1 = form.cleaned_data.get('image1') image2 = form.cleaned_data.get("image2") user = request.user ImageAndUser.objects.create( User=user, image=image1, image2=image2, image3=image3, ) return redirect('registration/accounts/photo.html') else: print(666) form = UserImageForm(request.POST or None) return render(request, 'registration/profile.html',{'form':form}) in profile.html <main> <div> <img class="absolute-fill"> <div class="container" id="photoform"> <form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data" role="form"> {% csrf_token %} <div class="input-group"> <label> <input id="image1" type="file" name="image1" accept="image/*" style="display: none"> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label> <input id="image2" type="file" name="image2" accept="image/*" style="display: none"> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label> <input id="image3" type="file" name="image3" accept="image/*" style="display: none"> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <input id="send" type="submit" value="SEND" class="form-control"> </form> </div> </div> </div> </main> in forms.py class UserImageForm(forms.ModelForm): image = forms.ImageField() class Meta: model = ImageAndUser fields = ('image1','image2','image3') I really cannot understand why this error happens.I surely send images so I think type is not None.What is … -
Send data to Django template via simple_tag
My aim is to draw plots with Echart library separate from my main view. Thar is why I created an custom template to send chart data to the template html file. If I do this with render method the data sending is working. I attach my working render view and the custom view (this would be my aim). Working view and template: View: def chart(request): data=Test.objects.all() data=[i['data'] for i in data] attr=[i['attr'] for i in data] bar = Bar("Teszt Chart") bar.add("Tropo",attr, data, is_stack=True) bar_chart = bar context = dict( myechart=bar_chart.render_embed(), host=DEFAULT_HOST, script_list=bar_chart.get_js_dependencies() ) return render(request, 'test/chart.html', context) Template <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Test chart</title> {% for jsfile_name in script_list %} <script src="{{host}}/{{jsfile_name}}.js"></script> {% endfor %} </head> <body> {{myechart|safe}} </body> </html> My custom template: (not working) View: register = template.Library() @register.simple_tag(takes_context=True) def chart(): data=Test.objects.all() data=[i['data'] for i in data] attr=[i['attr'] for i in data] bar = Bar("Teszt Chart") bar.add("Tropo",attr, data, is_stack=True) bar_chart = bar myechart=bar_chart.render_embed() host=DEFAULT_HOST script_list=bar_chart.get_js_dependencies() data={ 'myechart':myechart, 'host':host, 'script_list': script_list, } return data Template: <!DOCTYPE html> <html> {%load chart%} <head> <meta charset="utf-8"> <title>Proudly presented by PycCharts</title> {% for i in chart %} <script src="{{i.host}}/{{i.jsfile_name}}.js"></script> {% endfor %} </head> <body> {%for i in chart%} {{i.myechart}} {%endfor%} </body> </html> … -
Deploy Django/Python App to Heroku
I'm usign pyhon 2.7.14 but have errors when i tried to deploy my app. I'm working in windows. This is the build log: -----> Python app detected -----> Found python-3.6.4, removing -----> Installing python-2.7.14 -----> Installing pip -----> Installing requirements with pip Collecting backports.shutil-get-terminal-size==1.0.0 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 1)) Downloading backports.shutil_get_terminal_size-1.0.0-py2.py3-none-any.whl Collecting certifi==2018.1.18 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 2)) Downloading certifi-2018.1.18-py2.py3-none-any.whl (151kB) Collecting chardet==3.0.4 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 3)) Downloading chardet-3.0.4-py2.py3-none-any.whl (133kB) Collecting configparser==3.5.0 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 4)) Downloading configparser-3.5.0.tar.gz Collecting dj-database-url==0.4.2 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 5)) Downloading dj_database_url-0.4.2-py2.py3-none-any.whl Collecting Django==1.11.10 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 6)) Downloading Django-1.11.10-py2.py3-none-any.whl (6.9MB) Collecting django-bootstrap3==9.1.0 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 7)) Downloading django-bootstrap3-9.1.0.tar.gz Collecting enum34==1.1.6 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 8)) Downloading enum34-1.1.6-py2-none-any.whl Collecting flake8==3.5.0 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 9)) Downloading flake8-3.5.0-py2.py3-none-any.whl (69kB) Collecting gunicorn==19.7.1 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 10)) Downloading gunicorn-19.7.1-py2.py3-none-any.whl (111kB) Collecting idna==2.6 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 11)) Downloading idna-2.6-py2.py3-none-any.whl (56kB) Collecting mccabe==0.6.1 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 12)) Downloading mccabe-0.6.1-py2.py3-none-any.whl Collecting pathlib==1.0.1 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 13)) Downloading pathlib-1.0.1.tar.gz (49kB) Collecting pew==1.1.2 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 14)) Downloading pew-1.1.2-py2.py3-none-any.whl Collecting Pillow==5.0.0 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 15)) Downloading Pillow-5.0.0-cp27-cp27mu-manylinux1_x86_64.whl (5.8MB) Collecting pipenv==9.0.3 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 16)) Downloading pipenv-9.0.3.tar.gz (3.9MB) Collecting psutil==5.3.1 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt … -
Django Channels 2.0: call consumer via ChannelNameRouter from view
I am trying to upgrade my code from django-channels 1.1.8 to 2.0.0 So, I just want to perform a very simple async background task, and can not figure out why it does not print anything: routing.py from channels.routing import ProtocolTypeRouter, ChannelNameRouter from tasks.consumers import LongTask application = ProtocolTypeRouter({ 'channel': ChannelNameRouter({ 'long-task': LongTask }), }) consumers.py from channels.consumer import SyncConsumer class LongTask(SyncConsumer): def long_task(self, message): print(message) views.py def perform_long_task(request): channel_layer.send('long-task', { 'type': "long.task", 'text': 'Hey!' }) I guess something wrong here channel_layer.send('long-task', {...}) Big thx -
python ,django how to add paginator in python
Total No. of Transaction for the Current Month New User</th>--> Date User Vehicle Type Vehicle No Pump Company Pump Name Pump City Pump State Fuel Type Fuel Price Fuel Liters Total Amount Fuel Bill </tr> </thead> <tbody> {% for items in mmf_total_trans_today %} <tr> <!--<td width="20%">{{items.mmf_new_user}}</td>--> <td width="20%">{{items.date_updated}}</td> <td width="20%">{{items.user}}</td> <td width="20%">{{items.vehicle.vehicle_category}}</td> <td width="20%">{{items.registration_certificate}}</td> <td width="20%">{{items.company_ro}}</td> <td width="20%">{{items.fuel_station}}</td> <td width="20%">{{items.pump.city}}</td> <td width="20%">{{items.pump.indianstate}}</td> <td width="20%">{{items.fuel_type}}</td> <td width="20%">{{items.fuel_price}}</td> <td width="20%">{{items.fuel_total_litres}}</td> <td width="20%">{{items.fuel_total_price}}</td> <td width="20%">{{items.fuel_bill_upload}}</td> </tr> {% endfor %} <div class="pagination"> <span class="step-links"> {% if users.has_previous %} <a href="?page={{ users.previous_page_number }}">previous</a> {% endif %} <!-- Showing the page numbers in Html Page --> <span class="current"> Page {{ users.number }} of {{ users.paginator.num_pages }}. </span> {% if users.has_next %} <a href="?page={{ users.next_page_number }}">next</a> {% endif %} </span> </div> </tbody> </table> </div> in Models i have added paginator = Paginator(mmf_total_trans_today, 10) -
Fetching Data from multiple table in django
how i perform join query.. i want to fire query which act like.. "select s.nm,s1.sub from Student s,Subject s1"; here i show what i tried in django but doesn't work my model.py file is from django.db import models class Student(models.Model): sid = models.BigIntegerField(primary_key=True) nm = models.CharField(max_length=20, blank=True, null=True) id = models.ForeignKey('Subject', models.DO_NOTHING, db_column='id', blank=True, null=True) class Meta: managed = False db_table = 'student' class Subject(models.Model): id = models.IntegerField(primary_key=True) # AutoField? sub = models.CharField(max_length=30, blank=True, null=True) class Meta: managed = False db_table = 'subject' view.py from django.http.response import HttpResponse from django.core import serializers from App.models import Student, Subject # Create your views here. def fun(request): # obj1=Subject.objects.all() obj=Student.objects.filter(Subject.objects.all()).all() js=serializers.serialize("json",obj) return HttpResponse(js) but it doesn't solution.. please help me as soon as possible... fdhgjdfhjchnb ]ghnfghnghnghngf dhg hnfghnfghngfh hgfhhnldhnglhnklhn hkndhfgk fhknkghnkfgjh hnflkkhnhnhngfh hgfnh.gnjnml;fxmgnx; -
Django ORM get respective choices value instead of field value
In Django ORM, is there any way that you can directly get the respective choices value instead of the field value in the resulting Queryset. Example: port = models.CharField( max_length=5, choices=( ('21', 'FTP'), ('22', 'SSH'), (...), .. ) ) After the ORM Querying, I need the port name (not the number) in the Queryset itself. > myModel.objects.filter(...).values() > [{"id": 1, "port": "FTP"}, {"id": 2, "port": "SSH"}, {...}, ...] -
How to override (filter based on particular condition) Django admin filter choices?
My models Django are: class Brand(models.Model): name = models.CharField(max_length=200) class StanardProduct(models.Model): brand = models.ForeignKey(Brand) class VendorProduct(models.Model): standard_product = models.ForeignKey(StanardProduct) My model admin is: class StandardProductModelAdmin(admin.ModelAdmin): list_filter [ 'brand' ] In the list filter for 'brand', I want to show only those brand choices that satisfy following two conditions: Brand name choice should be referenced by StandardProduct object StandardProduct object should be referenced by VendorProduct object Using "admin.RelatedOnlyFieldListFilter" in the filter satisfies only condition no. 1 - but not no. 2. I need a way that satisfies both the conditions. -
{% empty %} does not work in django template
if works correctly but empty does not work, here is my code: {% for answer in ans|slice:":3" %} {% for course in crs %} {% if answer.course_id == course.id %} <h4 class="w3-text-blue">{{answer.course}}</h4> {% endif %} {% empty %} <h1>empty</h1> {% endfor %} {% endfor %} -
Creating a notification inbox similar to StackOverflow's using django-notifications-hq
I'm able to get to a point where the notifications will appear in the dropdown, but I'm losing hair trying to figure out an efficient way to make each individual notification a hyperlink to anywhere else in the site. I'm attempting to implement the live-updater on django-notifications-hq. Following along with their example and method of filling in the notification list, I've come to the conclusion that I need to configure the notify.js file. I figure that I should anchor a hyperlink to the notifications. So here is a very minimal example of a configured return statement in the notify.js file that will allow each notification to return a hyperlink: ... return '<li><a href="/">' + message + '</a></li>'; }).join('') In an attempt to make this more dynamic so that each notification leads to its appropriate page, I thought maybe I can implement context processors to fill each page with notification data-- context_processors.py: def notifications_unread(request): try: profile = Profile.objects.get(user__username=request.user) return {'unread': profile.user.notifications.unread()} except Profile.DoesNotExist: return {} And to use these variables in the JS file, I'd first run them through Django templates, and then make them available as global variables like so-- landing/notifications.html: <script type="text/javascript"> var currentUser = '{{request.user}}'; var notifications = … -
Error psycopg2 in Django
I installed psycopg2 == 2.7.3.2 and PostgreSQL 10.1 When I run djnago, I get an error, but I do not know how to fix it. I ask for help, comrades. Failed to get real commands on module "gattaca": python process died with code 1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/postgresql/base.py", line 21, in <module> import psycopg2 as Database File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psycopg2/__init__.py", line 50, in <module> from psycopg2._psycopg import ( # noqa ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psycopg2/_psycopg.cpython-35m-darwin.so, 2): Symbol not found: _PQbackendPID Referenced from: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psycopg2/_psycopg.cpython-35m-darwin.so Expected in: flat namespace in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psycopg2/_psycopg.cpython-35m-darwin.so During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/helpers/pycharm/_jb_manage_tasks_provider.py", line 25, in <module> django.setup() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 52, in <module> … -
How to access form data in `FormView.get_success_url()`
Currently, I have a form that looks like this: class SelectBoard(generic.FormView): form_class = forms.SelectBoard def form_valid(self, form): board_name = form.cleaned_data['name'] return redirect('leaderboard', board_name=board_name) However, it would be my preference to do the more idiomatic thing, and use get_success_url. Something like this: class SelectBoard(generic.FormView): form_class = forms.SelectBoard def get_success_url(self): form = ??? board_name = form.cleaned_data['name'] return reverse('leaderboard', board_name=board_name) However, the form is not passed to get_success_url, and unlike many other pieces of request context (like self.request, self.kwargs, or self.object (in DetailView)), the form is not attached as an attribute at any point in the standard FormView dispatch sequence. Is there any good way to access cleaned & validated form data in get_success_url (that is, without having to access self.request.POST or reconstruct the form from scratch)? -
save() prohibited to prevent data loss due to unsaved related object 'team'
When I create new team and trying to associate it to my User's Profile, I get this error is showing. I wanted a team that lot of members and only one creator(or admin of the team) and that creator is also member of the group. How can I associate team with User's Profile? Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) steam_id = models.IntegerField(unique=True, null=True) steam_name = models.CharField(max_length=255, null=True, unique=True) profile_pic = models.ImageField(upload_to='profile_images', default='profile_images/default_user.png', blank=True) rank = models.IntegerField(default=1) matches = models.IntegerField(default=0) kda = models.IntegerField(default=0) team = models.ForeignKey(Team, related_name='players', on_delete=models.CASCADE, null=True) class Team(models.Model): creator = models.ForeignKey(User, related_name='teams', on_delete=models.CASCADE) name = models.CharField(max_length=20, unique=True) rank = models.IntegerField(default=0) Views.py class TeamsCreateView(generic.CreateView): model = Team form_class = TeamCreationForm def form_valid(self, form): form.instance.creator = self.request.user self.request.user.profile.team = form.instance print(form.instance) print(self.request.user.profile.team) self.request.user.profile.save() return super().form_valid(form) -
Pagination on scroll don't work after AJAX update?
I use pagination on scroll of django-el-pagination app in my project. I show list of documents to user. Every such document has edit button. When user click to edit button he can see edit form. After successful editing I update list by AJAX. Problem is that after AJAX update the list pagination don't work anymore. In browser console I notice this error: TypeError: fragment.trim is not a function | el-pagination.js:72:50 It seems to me that I need to update/refresh pagination script in crud.js file. I put activatePagination function inside crud.js file but it didn't help me. Can you help me to fix this problem? main_template.html: <div id="documents" class="dd"> <ol class="dd-list"> {% include page_template %} </ol> </div> {% block script %} {# START: AJAX request to endless pagination #} <script type="text/javascript"> function activatePagination(){ $.endlessPaginate({ paginateOnScroll: true, onCompleted: function(context, fragment) { activateTooltip(); } }); } activatePagination(); </script> {# END: AJAX request to endless pagination #} <script src="{% static 'js/documents/crud.js'%}"></script> {# CRUD JS #} {% endblock %} crud.js: $(function () { $("#document-modal").on("submit", ".document-edit-form", function(e) {e.preventDefault(); saveForm.call(this, "Data successfully updated");}); var saveForm = function(success_message) { var form = $(this); var formData = new FormData(form[0]); $.ajax({ url: form.attr("action"), data: formData, type: form.attr("method"), dataType: 'json', success: … -
save django many to many relationship with through to database
I am new to django. I have a model named Person. I want to have a many to many relationship called interests. Each person has interests, interest is what I am going to implement. Each person has two types of interest: main interest and normal interest. Here is what I have: class Person(models.Model): person = models.ForeignKey(Profile, on_delete=models.CASCADE, verbose_name=_("person ")) interest = models.ManyToManyField( InterestList, through='interestRelation', through_fields=('person', 'interest'), ) class InterestList(models.Model): class Meta: verbose_name = _("interest list") title = models.CharField(_('interest list'), max_length=30) class interestRelation(models.Model): class Meta: verbose_name = _("interests' relation") is_main = models.BooleanField(_('is main'), default=False) person = models.ForeignKey(Person, on_delete=models.CASCADE) interest = models.ForeignKey(InterestList, on_delete=models.CASCADE) InterestList class has a fixed number of predefined interests, about 15. My problem is in serilizer. I want to have a serilizer which get the json as: ['main_interests':[a,b,c,d], 'normal_interests': [e,f,g]] my serilizer is going to have these two fileds: class InterestActionSerializer(serializers.Serializer): main_interests = serializers.JSONField() normal_interests = serializers.JSONField() def take_action(self, terminal): // what is my issue how can I save these items to database and setting the is_main flag True when needed? -
Django custom user model with hbase
I m pretty new to Django. I m using Hbase as my backend, I want to create the basic user functionality and more provided by django, I m not able to find anything relevant to my problem. any guidance would be appreciated. Thanks.