Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to django form takes a request
I have some problem. I wanna take a request in django forms but it may have some problem. here is my code. forms.py class PostForm(forms.ModelForm): CHOICES = request.user.fields() receive_user = fields.MultipleChoiceField(choices=CHOICES) content = forms.CharField(widget=PagedownWidget(show_preview=False)) publish = forms.DateField(widget=forms.SelectDateWidget) class Meta: model = Post fields = [ "receive_user", "content", ] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(MyForm, self).__init__(*args, **kwargs) and views.py `def post_create(request): if not request.user.is_authenticated(): raise Http404 form = PostForm(request.POST or None, request=request) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save()` and error message is NameError: name 'request' is not defined -
A golang equivalent to Django Rest Framework?
I've been using Django with Django Rest Framework for years and find it superb. That being said, I'm starting to work more in Go and would love to know of any equivalent library. The main features I care about are: The easy creation of a RESTful API from DB models Browsable API Easy support of different content types (json, yml, xml etc) Good support of linking/relations between models Good support for various auth methods Promotes or allows separation of concerns in consuming code I appreciate that there may not be an answer that fulfils all of the above, but a solution would need to satisfy a majority of them. I'd also be happy to hear about a small collection of libraries (2-3 max) that have been proven to work well together and fulfil the criteria. -
How to get the current user in ListView?
How do I get the current user in the following implementation of the ListView. I would like to use the 'current user' in the uname argument of reverse_lazy class ListMessages(ListView, ModelFormMixin): model = Message template_name = 'accounts/list_messages.html' context_object_name = 'messages' form_class = MessageHiddenUserForm success_url = reverse_lazy('accounts:list_messages', kwargs={'uname': }) -
Global VR Videolayer in Panotour
I'm creating a virtual pano tour with several different panoramas linked with a hotspot. On each panorama I have a video hotspot which plays a video. My problem is, that everytime a new scene loads, I have to touch the display for that the video loads... Panotour also explains, that this behaviour is normal Now I am looking for a solution, that I can play / stop all the videos with the first touch on entering the vr mode... I've created an array with all the videos and let them play/stop after the first touch but it just loads the videos from the first scene and not from all the other ones. I've also tried to make a global layer and insert the video source and position with javascript on the play button, but global layers aren't in VR stereo mode I've tried to put all the video hotspot on the first scene but that doesn't work either because it doesn't allow 2 hotspots with the same ID. Has anyone an idea how I can get all the videos playing with the first touch on entering the vr mode? Thank you very much Alex Panotour Pro 2.5.5 -
Invisible table borders ReportLab
I need to display some information on a ReportLab PDF that will be side by side. For example, below is a little pretend PDF. I have to have Thing 1 and Thing 2 beside eachother with information below them. --------------------------- | Thing 1: Thing 2: | | A-B-C 1-2-3 | | D-E-F 4-5-6 | | | | | ----------------------------- I used Paragraph to start, but I couldn't find a way to make Thing 1 and Thing 2 line up. So I was thinking about using a table. Is there a way I can have multiple tables on a PDF that all have invisible borders? Thanks! -
Django can't create object - RelatedObjectDoesNotExist
I have a model Payment and model Invoice. The model invoice has an attribute payment which is a OneToOneField field with null=True and blank=True. The problem is that Django doesn't allow me to create a payment. >>> Payment.objects.create(total_price=10) RelatedObjectDoesNotExist: Payment has no invoice. >>> Payment.objects.create(total_price=10,invoice=Invoice.objects.first()) TypeError: 'invoice' is an invalid keyword argument for this function Can't figure out why is that so. I want Invoice to have an optional argument payment and vice versa because Payment object is created after recieved payment. class Invoice(models.Model): identificator = models.UUIDField(default=uuid.uuid4, editable=False) order = models.OneToOneField('Job', related_name='invoice', on_delete=models.CASCADE) price_per_word = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=12) translator_revenue_in_percent = models.FloatField(null=True, blank=True) discount_in_percent = models.FloatField(default=0) final_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) estimated_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) paid = models.BooleanField(default=False) payment = models.OneToOneField('Payment', related_name='invoice', null=True, blank=True) __original_paid = None def save(self, *args, **kwargs): if not self.__original_paid and self.paid: self.__original_paid = True if self.order.translator: EventHandler.order_has_been_paid(self.order) super(Invoice, self).save(*args, **kwargs) class Payment(models.Model): payment_identifier = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) total_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) def save(self,*args,**kwargs): EventHandler.order_has_been_paid(self.invoice.order) super(Payment,self).save(*args,**kwargs) Do you know where is the problem? -
Move "Login link" to right side from Bootstrap navbar
I'm developing a Django website and I'm using Bootstrap/CSS/HTML in order to get an aesthetic look. I created a navbar menu and I would like to place my login tab to the right side. But, it's maybe be stupid, I don't get a good result : My HTML script looks like : {% if user.is_authenticated %} ... display all tabs ... <ul class="nav navbar-nav navbar-right"> <li><a href="{% url "logout" %}"><span class="glyphicon glyphicon-log-out"></span> Déconnexion </a></li> {% else %} <li><a href="{% url "login" %}"><span class="glyphicon glyphicon-log-out"></span> Connexion </align></a></li> {% endif %} </ul> If user is connected : And if user is not connected : I'm really new with HTML/CSS/Bootstrap so do you have any idea ? Thank you -
Can someone please show how I can get this traffic light working automatically?
<!DOCTYPE html> <html> <head> <title>Traffic Light</title> <style type="text/css"> .traffic-light { width: 100%; } .off { background-color: transparent!important; } .traffic-light { margin: 0 auto; width: 20%; min-width: 180px; border: 1px solid gray; } .traffic-light div { margin: 0 auto; width: 150px; height: 150px; border: 3px solid gray; border-radius: 50%; margin-top: 5px; margin-bottom: 5px; } .red { background-color: red; } .yellow { background-color: yellow; } .green { background-color: green; } </style> </head> <body> <div class="traffic-light"> <div class="light red off"></div> <div class="light yellow off"></div> <div class="light green off"></div> </div> <button type="button" onclick="cycle()">Next cycle</button> <button type="button" onclick="autoCycle()">Auto cycle</button> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js"></script> <script type="text/javascript"> var $tl = $('.traffic-light'), // Traffic light element $lights = $('.light', $tl), // All lights in one place states = [0, 4, 6, 1, 4]; // Binary states of traffic light function cycle() { var currentStateArr = $('.light', $tl).map(function (i, lightEl) { return ~~!($(lightEl).hasClass('off')); }).get(), currentStateNum = parseInt(currentStateArr.join(''), 2); // Converting current TL state to decimal number for more comfort if (currentStateNum === 0) { // If ALL lights are OFF and we are here then next is obviously red return $lights.addClass('off').siblings('.red').removeClass('off'); // and nothing to do here more } var nextStateIndex = states.indexOf(currentStateNum)+1, nextStateNum = (nextStateIndex === states.length) ? 0 … -
TypeError: undefined is not an object (evaluating '$.fn.dataTable.ext')
When click any category(tab) of Tabs, dataTable should remove other categories data. I follow this example - http://jsfiddle.net/d5hre2ux/ , but the system gives "TypeError: undefined is not an object (evaluating '$.fn.dataTable.ext')" error. here is my code. <script src="https://code.jquery.com/jquery-1.9.1.min.js" integrity="sha256-wS9gmOZBqsqWxgIVgA8Y9WcQOa7PgSIX+rPA0VL2rbQ=" crossorigin="anonymous"></script> <script type="text/javascript" src="{% static 'js/jquery.dataTables.min.js' %}"></script> <script> $('#alldataTable').DataTable({ }); var table1 = $('#alldataTable').DataTable(); $("#Tabs").click(function(event){ $.fn.DataTable.ext.search.push( function(settings, data, dataIndex) { var id = event.target.id; return $(table1.row(dataIndex).node()).attr('data-user') == id; } ); table1.draw(); }); $('#alldataTable tbody').on('click', 'tr', function () { var data = table1.row( this ).data(); window.location.href = "about" }); -
improve this query with django ORM
I have a Person model with name and city as attrs. I need a way to retrieve amount of people by city. I need a output like this dict: {"NY": 23, "CA": 30, ...} What I did was: response = {} for city in ["NY", "CA", ...]: response[city] = Person.objects.filter(city=city).count() but here I have to provide a predefined list with cities, and iterate over them. Exist any way with django ORM to do this directly, and avoid the loop? -
What does this regex mean in django?
I'm learning django from a book and I've got into advanced urls, in here there is a regex that it's not explained: urlpatterns = [ url(r'^(?P<page_slug>\w+)-(?P<page_id>\w+)/', include([ url(r'^history/$', views.history), url(r'^edit/$', views.edit), url(r'^discuss/$', views.discuss), url(r'^permissions/$', views.permissions), ])), ] I understand that it's about removing redundancy, but how does it actually work? Where do you get page_slug and page_id from and what's with the - between them? -
Printing Arabic characters in python/django
I have a script that modifies data in a django app.I have data in an excel file that i process then update my models with it, some of the data is in Arabic and when i execute the script i get the following error: Traceback (most recent call last): File "script.py", line 77, in <module> update_locations(path) File "script.py", line 36, in update_locations household.location = new_location File "/data/envs/ve.maidea/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 207, in __set__ self.field.remote_field.model._meta.object_name, ValueError: Cannot assign "'\xd8\xa7\xd9\x84\xd8\xa8\xd8\xad\xd9\x8a\xd8\xb1\xd9\x87'": "Household.location" must be a "Location" instance. I think the error is been raised by these Arabic characters. here is my script: import django django.setup() import sys reload(sys) # to re-enable sys.setdefaultencoding() sys.setdefaultencoding('utf-8') import xlrd from django.db import transaction from foodnet.apps.registration.models import Household from geo.models import Location log_file = "/opt/cv_instances/cv1/autodeploy/branches/nboreports/maidea/egypt/data_import_files/egypt_beheira_locations.txt" logfile_to_write = open(log_file, "w") def process_file(path): book = xlrd.open_workbook(path) print("Got {0} number of sheets.".format(book.nsheets)) hh_counter = 0 for sheet_num in range(book.nsheets-1, -1, -1): sheet = book.sheet_by_index(sheet_num) print("Processing sheet number {0} ({1})".format(sheet_num, sheet.name)) for row_idx in range(1, sheet.nrows): with transaction.atomic(): try: household_name = str(sheet.row_values(row_idx)[0]).strip().replace(".0","") # old_location = str(sheet.row_values(row_idx)[1]).strip().replace(".0","") new_location = str(sheet.row_values(row_idx)[2]).strip().replace(".0","") if household_name: household = Household.objects.get(office__slug='eg-co',name=household_name) # print(household.name, household.location) #update new locations household.location = new_location household.save() hh_counter += 1 logfile_to_write.write("Household {0} updated to location {1}".format(household, household.location)) … -
Django- understanding how information is displayed on webpage
I have recently taken over the development of a Django/ Python project, and am looking into fixing a particular bug within the system as it currently stands. There is a database of projects with quite a large amount of information about each project stored. On one of the webpages, there is a button, which when clicked will add a new form to the page- the form allows the user to enter some details about a new object for the given project. If there are existing objects for that project within the database, a 'table' will be displayed with a form on each row for each of the existing objects, and the user can manually update the fields in the form to update the information about each of the objects in the database. They can also add a new 'row' to the 'table' to create a new object to add to that project. This page is displayed by the view: def current_ccis(request, budget_id): """ View the CCIs for the current budget """ budget = Budget.objects.select_related('project').get(id=budget_id) project = budget.project ccis = CciItem.objects.select_related('budget', 'budget__project', 'project_room', 'project_room__room').filter(budget_id=budget_id).order_by('project_room__order', 'created') formset = CciItemFormset(queryset=ccis.exclude(name=None), form_kwargs={'project':project}) context = { 'ccis': ccis, 'project': project, 'budget': budget, 'formset': formset, 'widths': … -
Cannot assign must be instance on form save
I'm creating a site where users can publish their content, each content redirect to a private user to user chat depending on the content id. I'm doing it like this so I can retrieve the content infos on the private chat. The problem is that when a user submit the form to post a comment I get this error : Cannot assign "< User: my_user >": "userComment.seller" must be a "Profile" instance. On my view, I'm saving the connected user as a buyer and the user who will receive the comment as seller. How can I fix this error ? What am I doing wrong on the code below ? here is models.py : class Profile(models.Model): name = models.CharField(max_length=120) user = models.OneToOneField(User, null=True, blank=True) class Gig(models.Model): profile = models.ForeignKey(Profile, null=True) title = models.CharField(max_length=100, unique=True) class userComment(models.Model): buyer = models.ForeignKey(User, related_name="buyer", null=True) seller = models.ForeignKey(Profile, related_name="seller", null=True) comment = models.TextField(max_length=255, null=True) views.py def addComment(request, gig_id): gig = Gig.objects.get(id=gig_id) username = gig.profile.user if request.method == 'POST': form = userCommentForm(request.POST, request.FILES) if form.is_valid(): form.save(buyer=request.user) return HttpResponseRedirect('/') else: form = userCommentForm() form.fields['seller'].initial = username forms.py class userCommentForm(forms.Form): seller = CommaSeparatedUserField(label=_(u"seller")) comment = forms.CharField(label=_(u"comment"), widget=forms.Textarea()) def save(self, buyer): sellers = self.cleaned_data['seller'] comment = self.cleaned_data['comment'] message_list … -
Django. Map field from model to field in database table
I've got the following model: class MyModel(models.Model): field_one = models.CharField(max_length=255) field_two = models.CharField(max_length=255) class Meta: db_table = "super_table" and the following database table: CREATE TABLE public.super_table ( id integer NOT NULL DEFAULT nextval('super_table_id_seq'::regclass), field_two character varying(255) NOT NULL, field_three character varying(255) NOT NULL, ) can I somehow to map field_one in model with field_three in my super_table? -
py django not making tables in database, UnicodeDecodeError
I have tried everything and this is, for some reason, a repeating issue I've finally decided to ask help with. This has happened both locally and on Heroku in the past but right now it is just on Heroku. I cannot make tables in the database. I flushed and deleted (heroku pg:reset DATABASE_URL) the db, and I have tried running ./manage.py makemigrations and ./manage.py migrate (both with and without app name). They both work in that it adds the migrations to the db, but still does not create tables. Usually what magically fixes this, and does locally right now but not with the same files on heroku, is ./manage.py migrate --run-syncdb but it results in: File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 130, in handle "App '%s' does not have migrations." % app_label UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128) if I run the same command with the app_name, i get: File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) … -
Python error: No handlers could be found for logger “xhtml2pdf”
I am converting an HTML to pdf in django function, for this i am using xhtml2pdf pisa module, and the code is pdf = pisa.CreatePDF(html, file(settings.MEDIA_ROOT+'/tickets_pdf/'+pdfName, "w")) This code is working and generates pdf but sometime it works and sometime it doesn't work and give error No handlers could be found for logger “xhtml2pdf” There is also same question on SO that i have already checked. http://stackoverflow.com/questions/32997703/no-handlers-could-be-found-for-logger-xhtml2pdf But it did not work for me. If my client generates 10 times pdf then at least 4 times it gives this error and in other case it works fine. Is there any solution for this, or i have to generate pdf in other way. Thanks -
Git- link on local master branch works, doesn't work on live version
I am working on a Python/ Django project, using Git to manage the version control. I'm currently having an issue with some inconsistency between the master branch on my local machine and the live master branch on the server... I fixed a bug on my local machine earlier, and pushed the changes to the server, however, a link on one of the pages on the live version on the server is now no longer working, even though it is on my local version... The link is at: www.mysite.co.uk/costing/id/ - when I click on the link 'Reports', I get an error page that says: TemplateSyntaxError at /costing/6108/payment-report/overview/ Invalid block tag on line 87: 'date_to_display', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? But on my local machine, on the master branch, this link works correctly. Having looked at the template where the live version is complaining about the the invalid block tag, I can see that it is in the block: {% block content_payment_schedule %} {% if not webview %} <div> <table> <tr> ... </tr> <tr> <td> <span class="project-name">{{project.project_name|upper}}</span> </td> <!-- Display today's date in the header --> <td> {{ date_to_display }}</td> </tr> </table> </div> … -
Teamcity server on windows server architecture?
i have setup "Teamcity Server" on a windows instance and i wanted to deploy builds on ubuntu server (django app). As a new bee im a bit confused, how the whole teamcity architecture works in this scenario? Do i need to add or define my target ubuntu machine as a "Build Agent" in teamcity server? if Yes then, how im able to push those builds on to the target ubuntu server? -
nginx+gunicorn+django 502 bad gateway
I deployed a web app used with nginx+gunicorn+django,it got a 502 status when i did a test,in the nginx file,it reported: recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 192.168.1.170 how to fix the problem? -
Repeat fields in django forms
I would like to have a form containing three times two related fields (A name, and some ip address as a simple regex field) name1 name1 IPs name2 name2 IPs name3 name3 IPs name 1 and 2 are required, IPs are never. Is there a way not to repeat these fields, and/or better, to receive them as list or something like : [ { name, ip }, { name, ip }, { name, ip } ] Thanks -
request.data is empty in django REST API Request in AngularJS PATCH request from Safari
While I could access the request.datavalues from Django backend when the API (https://test.mysite.com/cart/) is triggered via Google Chrome, the same PATCH request when triggered from safari browser does not give me the request.data values. Request Details: URL: https://test.mysite.com/cart/ Request Type: PATCH Request Data: {"num_cases":6} While accessing data via PDB on the request object on Django. From Safari, From Chrome, -
Change one django form field value relative to another
Let say I have two fields in a django form country and state.I want the values of state to relatively change with the values of country.i.e. I want the state field to list out the states of the country that user has selected. Also the state field should be empty during form initiation.I know that this can be done using java script and other scripts.But,I would like to know if there are any conventional methods exists in django to do the same.??? -
How to render word files (.doc and .docx) in web application using python-docx?
I am trying to display docx files in web application. When I try to view the doc file it is downloading. I am not interested embedd any plugins. Using HttpResponse to display. I am using django. Anybody has any suggestions? -
How to get the current user in ModelFormMixin post() method?
How do i get the currently logged in user in the following implementation of the LIstview and ModelFormMixin: class ListMessages(ListView, ModelFormMixin): model = Message template_name = 'accounts/list_messages.html' context_object_name = 'messages' form_class = MessageHiddenUserForm #success_url = reverse_lazy('accounts:list_messages', kwargs={'uname': }) def post(self, request, *args, **kwargs): self.object = None self.form = self.get_form(self.form_class) if self.form.is_valid(): self.form.user_to = self.kwargs['uname'] self.form.user_from = request.user #this doesn't work self.object = self.form.save() return self.get(request, *args, **kwargs)