Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Checkboxes disappear when materializecss is applied (using django)
The code with the css makes the checkboxes disappear for cash and paytm. They have been initialised as boolean variables in the model(using django). <table> <thead> <tr> <th>Payment Method:</th> </tr> </thead> <tbody> <tr> <td>{{ seller_event_form.cash_payment }}</td> <td>{{ seller_event_form.paytm_payment }}</td> </tr> </tbody> </table> Without the css, the checkboxes appear. Because of this, none of the data inputted gets stored in the database. -
How to join with sub-table using Django's ORM?
I've this query. Orders post records by last comment on post. This query works well with small tables. However, I've filled database with random data approximately 2M rows on comment table. Analyzed query with explain and saw that sequential scan is performed on Post table. Post.objects.extra(select={'last_update': 'select max(c.create_date) from comment_comment c where c.post_id = post_post.id'}).order_by('-last_update') I've rewritten same query which is faster than current one. But I could not find a way to fit the query on django's orm. How can I rewrite it? If it is possible, I want to write it not using raw query as much as possible. Regards. Thanks for any help. select p.*, t.last_update from post_post p join ( select c.post_id as pid, max(c.create_date) as last_update from comment_comment c group by pid) t on p.id = t.pid order by t.last_update desc limit 50; -
Django CSRF failure when AngularJS sends blank cookie
There are several 'moving' parts to this problem. I'm going to start with a quick summary and hope someone has already seen this and can answer without all the gory details. Angular $http POST request fails with 403 error and "CSRF Failed: CSRF cookie not set." Correct CSRF cookie and header are definitely set in the reuqest as verified in development tab in Chrome. Chrome shows COOKIE header text in request as: Cookie: _ga=redacted; sessionid=redacted; ; csrftoken=redacted Happens in my dev environment on macOS. (Have not seen it on Linux.) I have done enough stepping through Django code to see that the raw cookie string, above, comes into the Django app in the HTTP_COOKIE field of the request but never makes it into request.COOKIE. I am convinced that Django's cookie text parser is thrown off by the extra semicolon in the raw cookie text. Assuming this is true I don't know if the parser is broken or AngularJS is broken since I don't know the official syntax requirements for raw cookie strings. But the easiest solution would be to figure out how to get Angular to drop that 'blank' cookie. Django 1.8 & AngularJS 1.6.7. -
text editing for string received from API
View gets data from API and send it to html as a value. the result is looking like "the comparable good was sold with a price $342234.0" The task is to format the numeric part of this string to get the view like "the comparable good was sold with a price $342,234.00" Trial to do it in view there this html was rendered brought zero result, while i was expecting at least a server crash. that in html is tag p {{info.data}} /tag p Can I fix this with any script or other way? who an advice? -
Django, PostgreSQL, Python3: how to use logarithm function
I have Post table with something like this: class Post(models.Model): likes = models.IntegerField() dislikes = models.IntegerField() timestamp = models.DateTimeField() I need to apply log function like this: log(max(abs(likes - dislikes), 1), 10) But I can't understand, how to connect raw SQL into Django query. -
Unable to Get Multiple Select Options
I'm trying to pull the selected options through AJAX into a django view. It's only printing out the first selected option, not the 2nd or 3rd and so on. If I pass a dictionary in the ajax, it receives it fine in the view. So the error is not in the view, since the getlist is gathering the dictionary. However, when I use the variable from the template.html, it only won't get more than 1 value. I've tried adding "[]" after the name and id, but no success. I've also tried some javascript from other answers on SO, but no results. template.html <div id="manytomany-container"> {% if custommany1.name != 'None' %} <label>{{ custommany1.name }}:</label> <p><select name="custommany1" multiple="multiple" id="company-custommany1"> {% if company.custom_many1 %} {% for selected in company.custom_many1.all %} <option selected="selected" name="custommany1" value="{{ selected }}">{{ selected }}</option> {% endfor %} {% for option in custommany1_options.all %} {% if option not in company.custom_many1.all %} <option name="custommany1" value="{{ option }}">{{ option }}</option> {% endif %} {% endfor %} {% else %} {% for option in custommany1_options %} <option name="custommany1" value="{{ option }}">{{ option }}</option> {% endfor %} {% endif %} </select></p> {% else %} <input type="hidden" id="company-custommany1"> {% endif %} </div> $(document).ready(function(){ $('#company-form-submit').click(function() { … -
Template rendering error Wagtail
When rendering a page, an error occurs Here is my base.html {% load static wagtailuserbar %} <!DOCTYPE html> <html lang="en"> <head> ... </head> <body> ... </body> </html> And i have template inside my App team_rooster/template/team_rooster.html with following code {% extends 'base.html' %} {% load staticfiles %} {% load wagtailcore_tags %} {% block content %} ... {% endblock %} -
How to add multiple many to many data in django shell
I have a player instance who played three leagues. in the player model class, I set many to many fields with league class. Now I want to add all 3 leagues to the player instance in Django shell. class League(models.Model): league = models.CharField(max_length=20) def __str__(self): return self.league class Player(models.Model): name = models.CharField(max_length=30) league_played = models.ManyToManyField(League, default='Unknown') -
django view retrieve all objects of foreign key of foreign key
I have three models as following: class Library(models.Model): library_id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) #This helps to print in admin interface def __str__(self): return u"%s" % (self.name) class Book(models.Model): book_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) # A book can have multiple authors and an author can have multiple books author = models.ManyToManyField('Author') # A library has many books which_library = models.ForeignKey('Library', related_name='books', on_delete=models.CASCADE) #This helps to print in admin interface def __str__(self): return u"%s" % (self.title) class Author(models.Model): author_id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) #This helps to print in admin interface def __str__(self): return u"%s" % (self.name) I want to retrieve all authors in a specific library. My view looks like following: @api_view(['GET', 'POST']) def author_list(request, library_id): """ List all authors in a specific library """ if request.method == 'GET': authors = Author.objects.get() serializer = AuthorSerializer(books, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = AuthorSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) What should I write in get() as my condition? UPDATE: my logic is: A library can have many books and a book can have many authors and and an author can have many books. -
How to assign a Django channel session to an object in ORM?
I have remote application that connects to the Django running Channels and opens websocket connection. I do not use Groups. The reason for opening websocket is only to have push notifications from Django. If I want to push a notification to a websocket connection opened by an User, how to find the opened connection (its reply_channel)? -
How to redirect from the Django login page to a single page application?
I am building a SPA React application that is served by a single Django view at /. I am using Django's admin page for login. If an unlogged in user navigates to /#/accounts/ the Django admin page will correctly them redirect to http://localhost:8000/admin/login/?next=/#/accounts/pp01/ for login. Once they log in, they get redirected to my Django view that is configured at the / url path. The #/account/pp01 part of the redirect gets lost and the user gets redirected to the wrong part of my single page application (http://localhost:8000/#/). Does anyone know how to get this to work? I don't understand why Django is cutting off the # part of the URL. Any insight would be appreciated. Thanks! -
Passing table values from template to view
I have template with table which is dynamically created by javascript. Then I want retrieve with submit button only value within <td name="plu"></td> tags and process it in view to save as json into CharField in model. I tried to use form tag with method post and request.POST.get('plu') in view but it won't work. I want to get that values and then process it with model methods. Here are parts of code: @login_required() def cash_register(request): """plus = [123,345,567] newtrans = Transaction() newtrans.set_plu_list(plus) newtrans.save()""" if request.method == 'POST': x = request.POST.get('plu', False) # ??? try: products = Product.objects.all().values_list('plu_num', 'art_name', 'sales_price_brutto') products_json = json.dumps(list(products), cls=DjangoJSONEncoder) except Product.DoesNotExist: raise Http404('Products cant\'t be found!') return render(request, 'panel/cash_register.html', {'products_json': products_json}) class Transaction(models.Model): plu_list = models.CharField(max_length=255) transaction_date = models.DateField(auto_now_add=True) is_ksk = models.BooleanField(default=False) ksk_num = models.IntegerField(null=True) def set_plu_list(self, x): self.plu_list = json.dumps(x) def get_plu_list(self): return json.loads(self.plu_list) And html: https://pastebin.com/RFn5qNn2 -
How can I remove existing fields in the default User DB in Django?
I have created and AbstractUser with some fields that I want the User Class to have. But after successfully creating a new User Model, the user table now has the previous columns (the ones which would have been added on migration of the default User Model) and also has the columns which I have added in the Custom User Model. Is there a way to remove the columns which are added by default? Here's my models.py class CustomUser(AbstractUser): ''' SOME UNIQUE FIELDS ''' class Meta: swappable = 'AUTH_USER_MODEL' db_table = 'users' These are the fields that appear even without specifying in the model. How can I get rid of them? -
Migration error Wagtail
I have following model classes in my App called "team_rooster" class Spieler(StructBlock): nummer = IntegerBlock(required=True) position = ChoiceBlock(choices=[ ('th', 'TH'), ], icon='cup') class TeamRooster(Page): team_name = models.CharField(max_length=100, default="") spieler = StreamField([ ('spieler', CardsBlock(Spieler(), icon="user")), ], default='', blank=True) content_panels = [ FieldPanel('team_name', classname="col12"), StreamFieldPanel('spieler'), ] and ill render it within views.py from django.shortcuts import render from .models import TeamRooster # Create your views here. def teams(request): teams = TeamRooster.objects.all() return render(request, 'team_rooster.html', { 'teams': teams}) and plus following template {% extends 'base.html' %} {% load staticfiles %} {% load wagtailcore_tags %} {% block content %} <div class="container"> {% for team in teams %} <div class="row"> <table border="2" width="100%"> <tbody> <tr> <th colspan="5">{{team.team_name}}</th> </tr> <tr> <td>{{team.spieler.nummer}}</td> <td>{{team.spieler.position}}</td> </tr> </tbody> </table> </div> {% endfor %} </div> {% endblock %} When I do a migration, I get an error: LookupError: App 'team_rooster' doesn't have a 'spieler' model. I tried to do the migration before commenting out the part of the code where the text "spieler" is present, but I still have a error. -
Python 3.5.1 on CentOS 6 - getting error "undefined symbol: PyCObject_FromVoidPtr" when restarting Apache
I'm trying to run Django on a server with CentOS and Apache2. Using mod_wsgi. I've created a project with django just to make the "It works!" to see everything is working. But when I try to run httpd I get: undefined symbol: PyCObject_FromVoidPtr And wsgi module fails to load. I'm using mod_wsgi-3.2. Has anyone gone through a similar problem? Thanks in advance. -
Django modelformset_factory showing previous data in the form even after supplying queryset argument
I'm trying to collect some data via a formset and send it into my db. My view: def newlist(request): if request.user.is_authenticated(): user = request.user print user if request.method == 'POST': userinfo_form = Userinfo(request.POST, instance = user.userinfo) seller_event_form = Seller_event(request.POST) #seller_event_items_form = Seller_event_items(request.POST) seller_event_items_formset = modelformset_factory(seller_event_items, Seller_event_items) seller_event_items_form = seller_event_items_formset(request.POST, queryset= seller_event_items.objects.none()) if userinfo_form.is_valid() and seller_event_form.is_valid() and seller_event_items_formset.is_valid(): userinfo_form.save() new_seller_event = seller_event_form.save(commit=False) new_seller_event.user = user new_seller_event.save() new_seller_event_items = seller_event_items_form.save(commit=False) new_seller_event_items.event_id = new_seller_event new_seller_event_items.save() return redirect('/home') # if a GET (or any other method) we'll create a blank form else: userinfo_form = Userinfo() seller_event_form = Seller_event() #seller_event_items_form = Seller_event_items() seller_event_items_formset = modelformset_factory(seller_event_items, Seller_event_items) return render(request, 'home/newlist.html', {'userinfo_form': userinfo_form, 'seller_event_form': seller_event_form, 'seller_event_items_form': seller_event_items_formset}) When I render the form like so in html: <form action="/home/newlist/" method="post"> {% csrf_token %} {{ userinfo_form.as_p }} {{ seller_event_form.as_p }} {{ seller_event_items_form.management_form}} {% for form in seller_event_items_form %} {{ form.as_p }} {% endfor %} <input type="submit"> </form> I still see the previous data in the rendered page despite providing an empty queryset argument. What am I doing wrong? -
django website deployment workflow
I'm looking for some information on lifecycle workflow for deploying and maintaining a django based website. I've setup an ubuntu server running apache, mysql and mod_wsgi. I've deployed my django website and can access it. My troublesome points are updates to the models of the website. After manually uploading my modified code, the web server doesn't detect changes to my models.py. (i'm also assuming any changes to the models.py - new columns or new models (tables) should be created in the mysql database automatically. Changes to the existing fields are picked up fine). Reading through several posts and articles, several suggested rebooting the server, clearing the .pyc files, and reloading apache2 or touching the .wsgi file. None of these created the changes to the mysql db. This leads me to a few areas: 1. build a better workflow for maintaining and deploying change. We are using GitHub for version control. 2. My assumption of changes to the models without running makemigrations/migrate is incorrect and I have to execute those commands on the production db using manage.py 3. there's an improperly configured component somewhere. Can anyone point me in a direction - articles or books - to improve our deployment configuration … -
Multiple django forms in modal windows for a single view
I'm working on simple expense tracking app. Below you can find the view with all user's Operations (expense or income): Based on this thread I implemented bootstrap modal window to display new operation form: Below you can find ManageOperations view which is responsible for displaying views presented above: class ManageOperations(ListView, FormView, OperationMixIn): model = Operation form_class = OperationForm template_name = "expenses/manage_operations.html" success_url = reverse_lazy('manage_operations') def get_context_data(self, **kwargs): context = super(ManageOperations, self).get_context_data(**kwargs) context['operations_list'] = Operation.objects.filter(user=self.request.user).order_by('-date') return context def get_form_kwargs(self): kwargs = super(ManageOperations, self).get_form_kwargs() kwargs.update(user=self.request.user, initial={'account': Account.objects.get(user=self.request.user, default=True)}) return kwargs def form_valid(self, form): operation = form.save(commit=False) operation.currency = Account.objects.get(pk=form.instance.account_id).currency self.update_account_balance(form) form.instance.user = self.request.user form.save() return super(ManageOperations, self).form_valid(form) I'd like to implement same modal windows both for "edit" and "delete" actions. I assume that it will be quite simple for OperationDelete view: class OperationDelete(DeleteView, OperationMixIn): model = Operation success_url = reverse_lazy('manage_operations') def delete(self, *args, **kwargs): self.restore_account_balance(self.get_object().pk) return super(OperationDelete, self).delete(*args, **kwargs) I could just move delete method to my ManageOperations view and make it inherit from DeleteView. Things are getting more complicated when it comes to editing existing Operation. Currently following code is responsible for handing an update of existing entry: class OperationUpdate(UpdateView, OperationMixIn): model = Operation form_class = OperationForm success_url = reverse_lazy('manage_operations') def … -
TypeError at /admin/blogsite/articles/add/ when use markdownx
the error is coming when i use markdownx if i used markdownxfield() then i will can't to editor the model in admin 。the error is such as this: TypeError at /admin/blogsite/articles/add/ 'set' object is not reversible Request Method: GET Request URL: http://127.0.0.1:8000/admin/blogsite/articles/add/ Django Version: 2.0 Exception Type: TypeError Exception Value: 'set' object is not reversible Exception Location: C:\Users\liano\Desktop\python\blog\blog_venv\lib\site-packages\django\forms\widgets.py in merge, line 114 Python Executable: C:\Users\liano\Desktop\python\blog\blog_venv\Scripts\python.exe Python Version: 3.6.2 so why?and how to solve it ?thank u ! -
Check the form input value to existing value in Django
In in my database there are some email's those should be checked with the form value which is entered in email field models.py class Friend(models.Model): email = models.EmailField(max_length=100) forms.py class FriendForm(forms.ModelForm): class Meta: model = Friend fields = ['email'] views.py def check(request): if request.method == "POST": form = FriendForm(request.POST) if form.is_valid(): queryset = Friend.objects.all return render(request,"two.html",{"queryset":queryset}) else: form = FriendForm() return render(request, 'emaill.html', {'form': form}) emaill.html <body> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" name="Submit"> </form> </body> two.html <body> <h1>found</h1> {% for obj in queryset %} {{obj.email}} </br> {% endfor %} </body> when user submited any email that should be checked with models email that means with existing one if matches in should render to two.html it should show connect if mail does not match with mail that is in database it should show no such mail i am new to django so please help me -
How can I upgrade plan on Heroku from hobby-dev to hobby-basic?
I would like to upgrate plan on Heroku with my Django app from hobby-dev to hobby-basic. At the moment heroku pg:info returns: Plan: Hobby-dev Status: Available Connections: 0/20 PG Version: 9.6.4 Created: 2017-11-12 19:20 UTC Data Size: 135.9 MB Tables: 19 Rows: 1272760/10000 (Above limits, access disruption imminent) Fork/Follow: Unsupported Rollback: Unsupported Continuous Protection: Off Add-on: postgresql-cub... I tried to use Upgrading Heroku Postgres Databases but I am not sure which way should I choose. It seems to be that pg:copy would be the best idea? I think that steps in this case should look as shown below, am I right? 1.heroku addons:create heroku-postgresql:standard-0 2.heroku pg:wait 3.heroku maintenance:on 4.heroku pg:copy DATABASE_URL HEROKU_POSTGRESQL_PINK --app sushi How can I check DATABASE_URL and HEROKU_POSTGRESQL_PINK? I quess that DATABASE_URL is in Config Vars and this is it postgres://gxapb...2840@ec2-77-131-196-1207.compute-1.amazonaws.com:5432/d...md, isn't it? But how can I generate HEROKU_POSTGRESQL_PINK? I found information that it is the target database. 5.heroku pg:promote HEROKU_POSTGRESQL_PINK 6.heroku maintenance:off -
Django: redirect to view with parameters
I am using Django authentication. Whenever a user logs in, I want to redirect him to /profile/user_id, being user_id a number. I can get the value of user_id by request.user.profile.id. In settings.py I have LOGIN_REDIRECT_URL = 'app_1:index' app_1/urls.py: url(r'^profile/$', views.index, name='index'), # ex: /profile/5/ url(r'^profile/(?P<user_id>[0-9]+)/$', views.profile, name='profile'), app_1/views.py (things I've also tried are commented): def index(request): userid = request.user.profile.id #return render(request, 'app_1/index.html', context) #return profile(request, request.user.profile.id) #return render(request, 'app_1/user_prof.html', {'user': request.user.profile.id}) #return redirect(profile, user_id= request.user.profile.id) return redirect('profile', user_id=userid) def profile(request, user_id): user = get_object_or_404(Profile, pk=user_id) return render(request, 'app_1/user_prof.html', {'user': user}) I must be missing something because this should be easy but I'm stuck on it. Thanks in advance. -
can i host django web app using my own domain using firebase hosting?
I wish to use same database for my website which i wish to develop using python django and for the android app which will be hosted using fire base. Is it possible, please mention give details? Is there any other suggestions? Thank you in advanced..... -
Chrome Application Cache deleted when going Offline
I intend using a Service Worker to make a Web App available offline. The cache Storage shows the files when I have Internet Connection. However if I go Offline the cache seems to disappear. I do not have enabled the checkbox of Update on Reload in the Service Workers tab. The fetch event of my service worker is: self.addEventListener('fetch', function(e) { console.log('[ServiceWorker] Fetch', e.request.url); e.respondWith( caches.match(e.request).then(function(response) { return response || fetch(e.request); }) ); }); When I am Online the print for the console is: An unknown error occurred when fetching the script. Failed to load resource: net::ERR_INTERNET_DISCONNECTED service-worker.js However when I am offline the console ouptut is the following: [ServiceWorker] Fetch https://cocoa.pythonanywhere.com/static/login/bootstrap/CSS/bootstrap.css service-worker.js:113 [ServiceWorker] Fetch https://cocoa.pythonanywhere.com/static/login/logo.png cocoa.pythonanywhere.com/:1 Adding master entry to Application Cache with manifest https://cocoa.pythonanywhere.com/static/login/Offline/HTML/manifesto service-worker.js:113 [ServiceWorker] Fetch https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css service-worker.js:113 [ServiceWorker] Fetch https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js service-worker.js:113 [ServiceWorker] Fetch https://cocoa.pythonanywhere.com/static/login/js/app.js service-worker.js:113 [ServiceWorker] Fetch https://cocoa.pythonanywhere.com/static/login/bootstrap/js/jquery-3.1.1.min.js service-worker.js:113 [ServiceWorker] Fetch https://cocoa.pythonanywhere.com/static/login/bootstrap/js/bootstrap.min.js service-worker.js:113 [ServiceWorker] Fetch https://cocoa.pythonanywhere.com/static/login/js/diem.js cocoa.pythonanywhere.com/:1 Slow network is detected. Fallback font will be used while loading: https://cocoa.pythonanywhere.com/static/login/bootstrap/fonts/glyphicons-halflings-regular.woff2 app.js:2 CLIENT: service worker registration in progress. app.js:4 CLIENT: service worker registration complete. When I am Online the application tab looks: The Application Cache is poblated and the Service Worker registered. When I am Offline it appears … -
celery-django workers are exiting with code = 1 and no explanation given
I'am using celery with django on windows, the problem is that for some reason i get this error without any explanation: [2017-12-09 21:32:22,444: DEBUG/MainProcess] | Worker: Starting Pool [2017-12-09 21:32:22,650: DEBUG/MainProcess] ^-- substep ok [2017-12-09 21:32:22,650: DEBUG/MainProcess] | Worker: Starting Consumer [2017-12-09 21:32:22,650: DEBUG/MainProcess] | Consumer: Starting Connection [2017-12-09 21:32:23,674: INFO/MainProcess] Connected to redis://localhost:6379// [2017-12-09 21:32:23,674: DEBUG/MainProcess] ^-- substep ok [2017-12-09 21:32:23,674: DEBUG/MainProcess] | Consumer: Starting Events [2017-12-09 21:32:24,414: ERROR/MainProcess] Process 'Worker-1' pid:7088 exited with 'exitcode 1' [2017-12-09 21:32:24,686: DEBUG/MainProcess] ^-- substep ok [2017-12-09 21:32:24,687: DEBUG/MainProcess] | Consumer: Starting Heart [2017-12-09 21:32:25,263: ERROR/MainProcess] Process 'Worker-4' pid:9908 exited with 'exitcode 1' [2017-12-09 21:32:25,265: ERROR/MainProcess] Process 'Worker-3' pid:4664 exited with 'exitcode 1' [2017-12-09 21:32:25,265: ERROR/MainProcess] Process 'Worker-2' pid:3880 exited with 'exitcode 1' [2017-12-09 21:32:25,694: DEBUG/MainProcess] ^-- substep ok [2017-12-09 21:32:25,694: DEBUG/MainProcess] | Consumer: Starting Mingle [2017-12-09 21:32:25,694: INFO/MainProcess] mingle: searching for neighbors [2017-12-09 21:32:28,661: ERROR/MainProcess] Process 'Worker-8' pid:6016 exited with 'exitcode 1' [2017-12-09 21:32:28,661: ERROR/MainProcess] Process 'Worker-7' pid:8124 exited with 'exitcode 1' [2017-12-09 21:32:28,661: ERROR/MainProcess] Process 'Worker-6' pid:6248 exited with 'exitcode 1' [2017-12-09 21:32:28,663: ERROR/MainProcess] Process 'Worker-5' pid:7396 exited with 'exitcode 1' how can I find why the workers are exiting? I've enabled debug mode: celery worker --config=myapp.settings --loglevel=DEBUG but still no …