Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, Creating multiple forms for one sumbit button, using crispy and generic views
I want to create a Person and Assign that Person to a room with the same Form, Model is like Person --> Room using foreign key idPerson Model Person class Persona(models.Model): nombre = models.CharField(max_length=50) apellido_paterno = models.CharField(max_length=50) apellido_materno = models.CharField(max_length=50) id_documento = models.CharField(max_length=50) id_tipo_documento = models.ForeignKey(TipoDocumento, on_delete=models.CASCADE) id_genero = models.ForeignKey(Genero, on_delete=models.CASCADE) fecha_nacimiento = models.DateField(auto_now=False, auto_now_add=False, default= datetime.now) def get_absolute_url(self): return reverse('residentes:detalle', kwargs={'pk': self.pk}) def __str__(self): return self.nombre + ' - ' + self.apellido_paterno class Meta: unique_together = ('id_documento', 'id_tipo_documento') Model Resident class Residente(models.Model): persona = models.ForeignKey(Persona, on_delete=models.CASCADE) unidad_alquiler = models.CharField(max_length=5) tipo = models.CharField(max_length=50) fotografia = models.CharField(max_length=500) activo = models.BooleanField(default=True) def __str__(self): return str(self.persona.pk) + '-' + self.tipo + ' - ' + self.persona.nombre + ' ' + self.persona.apellido_paterno Views class ResidenteCreate(CreateView): model = Residente template_name = 'residentes/residente_form.html' form_class = ResidenteForm second_form_class = PersonaForm success_url = reverse_lazy('residentes:detalle') def get_context_data(self, **kwargs): context = super(ResidenteCreate, self).get_context_data(** kwargs) if 'form' not in context: context['form'] = self.form_class(self.request.GET) if 'form2' not in context: context['form2'] = self.second_form_class(self.request.GET) return context def post(self, request, *args, **kwargs): self.object = self.get_object form = self.form_class(request.POST) form2 = self.second_form_class(request.POST) if form.is_valid() and form2.is_valid(): residente = form.save(commit=False) residente.persona = form2.save() residente.save() return HttpResponseRedirect(self.get_success_url()) else: return self.render_to_response(self.get_context_data(form=form, form2=form2)) I see the 2 forms as one, … -
How can I upgrade PostgreSQL database on Heroku?
I am going 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- ... 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 guess 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 -
AttributeError at /accounts/regist_save/ 'User' object has no attribute 'user'
AttributeError at /accounts/regist_save/ 'User' object has no attribute 'user' error happens.I wrote in views.py I wrote in views.py def regist(request): regist_form = RegisterForm(request.POST or None) profile_form = ProfileForm(request.POST or None) context = { 'regist_form': regist_form, 'profile_form': profile_form, } return render(request, 'registration/regist.html', context) @require_POST def regist_save(request): regist_form = RegisterForm(request.POST or None) profile_form = ProfileForm(request.POST or None) if request.method == "POST" and regist_form.is_valid() and profile_form.is_valid(): regist = regist_form.save(commit=False) regist.is_staff = True regist.save() profile = profile_form.save(commit=False) profile.user = regist.user sex = request.POST.get("sex", "") year = request.POST.get("year", "") month = request.POST.get("month", "") day = request.POST.get("day", "") profile.sex = sex profile.year = year profile.month = month profile.day = day profile.save() else: print(regist_form.errors) print(profile_form.errors) return render(request, 'registration/detail.html') in regist.html <div class="form-group-lg"> <label for="id_username">Username</label> {{ regist_form.username }} </div> <div class="form-group-lg"> <label for="id_email">Email</label> {{ regist_form.email }} </div> <div class="form-group-lg"> <label for="id_password">Password</label> {{ regist_form.password1 }} </div> <div class="form-group-lg"> <label for="id_password">Password2</label> {{ regist_form.password2 }} <p class="help-block">{{ regist_form.password2.help_text }}</p> </div> {% load static %} <div class="form-group-lg"> <label for="birthday">Date</label> <select id="year" class="form-control year" name="year"> <option value="">--</option> </select> Year <select id="month" class="form-control month" name="month"> <option value="">--</option> </select> Month <select id="day" class="form-control day" name="day"> <option value="">--</option> </select> Day <br> <br> </div> <div class="form-group-lg"> <label for="sex">SEX</label> <select id="sex" class="form-control sex" name="sex"> <option value="">--</option> <option value="male">male</option> … -
localhost:9200 shows elasticsearch version as 6.0.1 after reinstalling 5.0.1
Previously I tried using elasticsearch 6 with django-haystack 2.6.1 for full text searching. I came to know that haystack does not support elasticsearch v6 so I deleted it. The steps I did for deleting and reinstalling are rm -rf es/ (I copied the elasticsearch in this folder) I downloaded the elasticsearch 5.0.1 from official website mv Downloads/elasticsearch-5.0.1.tar.gz es/ tar -zxvf elasticsearch-5.0.1.tar.gz cd elasticsearch-5.0.1 ./bin/elasticsearch -d I then run the following command in the terminal curl -XGET 'http://localhost:9200' My configuration HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack_furnitures', }, } The tech I am using macos, django==1.11.6, django-haystack==2.6.1, elasticsearch==5.0.1 and elasticsearch in a system the same version -
Why do I need to create a virtual environment for my public Django application?
I've been running my Django project (website) in my local virtual environment. However I now want to go live and make the website public - so I've created my remote server on Digital Ocean, and have been following it's tutorial on settings up Django. However I've reached this point in the tutorial where it says to create a virtual environment. I thought virtual environments were only used for testing your application offline? Why do I need a virtual environment for my application running on a remote server? -
Angular + DJango or Angular + Node Js
which one is best combination for e-commerce website with chatting functionality and Google Maps? First is Angular + DJango and second is Angular + Node. Why one of them is better? Which is easy to learn and manage? -
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 !