Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rendering fields manually and custom css class
I am trying to manually render the form fields. I would like to add a bootstrap and custom css class to rendered html. How can I do this ? forms.py class OrderCreateForm(forms.ModelForm): # rabat = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect()) class Meta: model = Order fields = ['postal_code'] widgets = { 'postal_code': forms.RadioSelect(), } file.html <form action="." method="post" class="order-form"> <div class="fieldWrapper"> {{ form.postal_code }} </div> <p><input type="submit" value="Send"></p> {% csrf_token %} </form> {% endblock %} rendered html <div class="fieldWrapper"> <ul id="id_postal_code"> <li><label for="id_postal_code_0"><input type="radio" name="postal_code" value="Yes" required id="id_postal_code_0" />Yes</label></li> <li><label for="id_postal_code_1"><input type="radio" name="postal_code" value="No" required id="id_postal_code_1" />No</label></li> </ul> </div> How to solve a problem ? I would appreciate your help. -
Modify Activation Complete - Django-Registration-Redux
I am trying to modify the view/url users are sent to once they have successfully activated their account via the link they are sent in an email. Here Read The Docs it goes some way to explaining it but I must be missing a trick somewhere: Two views are provided: registration.backends.default.views.RegistrationView and registration.backends.default.views.ActivationView. These views subclass django-registration-redux‘s base RegistrationView and ActivationView, respectively, and implement the two-step registration/activation process. Upon successful registration – not activation – the default redirect is to the URL pattern named registration_complete; this can be overridden in subclasses by changing success_url or implementing get_success_url() Upon successful activation, the default redirect is to the URL pattern named registration_activation_complete; this can be overridden in subclasses by implementing get_success_url(). Imports in my apps Urls.py (I know I only need one, just trying both): from registration.backends.default.views import ActivationView from registration.backends.default.views import RegistrationView My class (I've tried with ActivationView as well): class MyRegistrationView(RegistrationView): def get_success_url(self,user): return reverse('profiles:step2', kwargs={'userid':request.user.id}) My modified URLs: url(r'^accounts/activate/complete/$', MyRegistrationView.as_view(), name='registration_activation_complete'), url(r'^accounts/', include('registration.backends.default.urls')), ... The reverse URL is good, I can access it via manually entering the URL but when I click the link in the email to activate, I get redirected to the register page BUT I am … -
How to save GeoJSON using GeoFeatureModelSerializer through POST - Django
I want to save GeoJSON from a HTTP POST request using the GeoFeatureModelSerializer serializer, however, the serializer.is_valid() method returns False so I can't even get to saving it. An example of the GeoJSON im trying to use is the following: { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "MultiLineString", "coordinates": [ [ [ -6.2511348724366, 53.340854644776 ], [ -6.2511348724366, 53.340854644776 ] ] ] }, "properties": { "start": "2017-04-14T22:57:21Z", "end": "2017-04-14T22:57:22Z", "created": "2017-04-14T22:57:54.037503Z", "owner_id": 1, "activity_type": "RUN" } } ] } I have a GeoFeatureModelSerializer subclass: class ActivitySerializer(GeoFeatureModelSerializer): class Meta: model = Activity geo_field = 'route' id_field = False fields = ('start', 'end', 'route', 'created', 'owner_id', 'activity_type') My APIView class has the following method for POST request serializer_class = ActivitySerializer def post(self, request, format=None): try: serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) else: return Response(status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response(status=status.HTTP_400_BAD_REQUEST) The documentation doesn't mention a way to save data that is GeoJSON. https://github.com/djangonauts/django-rest-framework-gis/blob/master/README.rst The model for the Activity is the following: class Activity(models.Model): id = models.AutoField(primary_key=True) start = models.DateTimeField() end = models.DateTimeField() owner = models.ForeignKey( User, verbose_name="owner", on_delete=models.CASCADE, default=1 ) activity_type = models.CharField( max_length=100, verbose_name="activity_type" ) created = models.DateTimeField( auto_now_add=True ) route = models.MultiLineStringField(verbose_name="route", default=MultiLineString) -
Loading pickle files from another python file
I have a TFIDF vectorizer that I need to use later on to find the most relevant documents, so I saved it as pickle file. This is the code I used to pickle the file vectorizer = TfidfVectorizer() tfidf_matrix = vectorizer.fit_transform(my_text_data) import six.moves.cPickle as pickle with open('vectorizer.pk', 'wb') as fin: pickle.dump(vectorizer, fin) I am using this pickle file inside a django app to find the most relevant documents when a user enters a query. So in one of the codes that is called by the views.py file, I am loading that pickle file import six.moves.cPickle as pickle tfidf_vectorizer = pickle.load(open("vectorizer.pk", "rb" )) But I get the following error AttributeError: Can't get attribute 'preprocess_text' on <module '__main__' from 'manage.py'> When I simply import the preprocess_text function and read the pickle file in another window without intiating the django app it works fine, but on running it inside a django app causes this error. Any ideas on what should be done? Thanks in advance. -
Hinting in django model Meta - pycharm
Trying to build something similar I am wondering how pycharm (and other tools) know what members to hint in django's model meta: With this simple model: class MyModel(models.Model): class Meta: db_table = "bla" app_label ="blub" when I hit completion it completes all the options (like db_table). Looking at the code here: https://docs.djangoproject.com/es/1.11/_modules/django/db/models/options/ I could not find any generic hint on how to determine which members the Meta class might have. Is it just dark magic or do i oversee something? -
How to implement machine learing algorithms in a web applications?
I am working on a webapp whose backend is written in django,I am trying to provide news feed like feature to user(u can say like facebook). I think using machine learing algorithms results will be more efficient. Now coming to main question,i've no prior experience in machine learning and want to learn how can i implement machine learning algorithms in my webapplication? Any information will be helpful,Thankyou in advance. -
Django upload file
I have created a model Document a few weeks ago it was working, I don't remember what I did, but I'm now getting the following error whenever I try to save it in the django-admin page: expected string or buffer It points this line: super(Document, self).save(*args, **kwargs) class Document(models.Model): category = models.ForeignKey(DocumentCategory, related_name='%(class)s') name = models.CharField(max_length=64) description = models.CharField(max_length=64) datafile = models.FileField() date = models.DateField() is_inactive = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.id is None: self.date = timezone.now().date print(self.datafile.url) extension = os.path.splitext(self.datafile.name)[1][1:] time_stamp = timezone.now() self.datafile.name = self.name + '_' +\ self.category.category + '_' +\ str(time_stamp.year) +\ '_' + str(time_stamp.month) +\ '_' + str(time_stamp.day) +\ '_' + str(time_stamp.hour) +\ '_' + str(time_stamp.minute) +\ '_' + str(time_stamp.second) +\ '_' + str(time_stamp.microsecond) +\ '.' + extension super(Document, self).save(*args, **kwargs) Apr 24 13:19:06 intranet gunicorn[2085]: response = wrapped_callback(request, *callback_args, **callback_kwargs) Apr 24 13:19:06 intranet gunicorn[2085]: File "/py_venvs/microsoft_app_venv/lib/python3.4/site-packages/django/contrib/admin/options.py", line 544, in wrapper Apr 24 13:19:06 intranet gunicorn[2085]: return self.admin_site.admin_view(view)(*args, **kwargs) Apr 24 13:19:06 intranet gunicorn[2085]: File "/py_venvs/microsoft_app_venv/lib/python3.4/site-packages/django/utils/decorators.py", line 149, in _wrapped_view Apr 24 13:19:06 intranet gunicorn[2085]: response = view_func(request, *args, **kwargs) Apr 24 13:19:06 intranet gunicorn[2085]: File "/py_venvs/microsoft_app_venv/lib/python3.4/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func Apr 24 13:19:06 intranet gunicorn[2085]: response = view_func(request, *args, **kwargs) Apr … -
how can i save ModelForm data to database
I know i should probably not open another thread for this question because it has been asked and answered so many times here.Yes I've worked through the tutorials and browsed the web a lot - what I have is mix of what I'm finding here and at other sites but Im having a hard time saving form inputs in the database. some one should please come to my rescue i have been trying to get this done for 3 days now, its very frustrating. here are my codes models.py class QuestionBank(models.Model): First_Semester ='First_Semester' Second_Semester ='Second_Semester' Semesters = ((First_Semester, 'First_Semester'),(Second_Semester, 'Second_Semester')) level = models.ForeignKey(ClassLevel) CourseTitle = models.CharField(max_length=50, null=False) CourseCode = models.CharField(max_length=10, null=False ) CourseUnit = models.IntegerField() Semester = models.CharField(max_length=20, choices=Semesters, default="Select_Semester") Date = models.DateField() question_papers = models.FileField(upload_to = 'QuestionPapers') def __str__(self):`enter code here` return '%s %s %s %s %s %s %s' %(self.level, self.CourseTitle, self.CourseCode, self.CourseUnit, self.Semester, self.Date, self.question_papers ) forms.py class QuestionBankForm(forms.ModelForm): class Meta: model = QuestionBank fields = ('level', 'CourseTitle', 'CourseCode', 'CourseUnit', 'Semester', 'Date', 'question_papers' ) views.py def uploadQpapers(request): context = RequestContext(request) if request.method == 'POST': Qpapers = QuestionBankForm(data=request.POST) if Qpapers.is_valid(): Qpapers.save() return render_to_response("Qbank/uploadQpapers.html", {'Qpapers':Qpapers}, context) else: return HttpResponse('INVALID') i want to be able to upload past questions and save … -
Django named URL parameters no longer working after upgrade to 1.1x
I have an old Django app which uses the URL template tag this way: {% url 'smart_service.views.view_name' %} So far it worked greatly, but after the update to version 1.1 nothing works anymore and any use made that way returns NoReverseMatch. I can solve this problem by putting app_name = 'smart_service' into my urls.py file and by changing the url tag to this: {% url 'smart_service:view_name' %} This is a tedious task and very prone to errors, I'd like to avoid it unless strictly necessary. Is the first use-case been deprecated? If not, why isn't it working anymore? -
testing in django: what are differences between setUpTestData and setUpClass in TestCase class?
What are the differences between setUpTestData and setUpClass in the TestCase class? More specifically, what are the use cases for each? -
Get input from drop down into Python inside Django app
I've been stuck on this issue for a few weeks as I'm not very familiar with how to get the ajax set up. I'm working on a Django app which is basically one page that has a Dropdown menu. I would like to get whatever the user selects from the Dropdown menu and pass that data into my views.py so I can use that information to display a graph. Right now the graph part is working (I can pass in hard coded data into it and it will generate the graph) and my dropdown is working as well. However, I don't know how to get data from the drop down into my views.py. Here is how it looks. Display.html {% extends "RecordEvent/nav.html" %} <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> </head> {% block content %} <div class="row"> <div class="padded"> <div class="download-header"> <h3>Logs</h3> <div class="row inline download-header"> <div class="col-lg-6"> <div class="dropdown padding col-lg-6"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> <span id="dropdownTitle" class="">Measurable</span> <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> {% include 'RecordEvent/includes/EntryDropdown.html' %} </ul> </div> </div> </div> </div> </div> </div> <div class='padded'> <div class='col-sm-12' url-endpoint='{% url "api-data" %}'> <h1>Graph Data</h1> <canvas id="myChart" width="400" height="400"></canvas> </div> </div> <script> {% block jquery %} var endpoint … -
Django: Sum up Counts in one query
I have a list of elements that i would like to rank according to the count of related manytomany elements. I think aggregating the counts of those source elements is the right way, but i haven't found a solution yet. class Element(models.Model): Source1 = models.ManyToManyField(Source1) Source2 = models.ManyToManyField(Source2) Source3 = models.ManyToManyField(Source3) Ranked = (Link.objects.all().aggregate( Ranked=Sum(F('Source1') + F('Source2') + F('Source3'), output_field=IntegerField)['Ranked'] )) -
How to structure a website using given technologies?
Hello everyone and thank you for your time! I have a school project where I have to build a full responsive website in less than 2 months but the trick is that we have to use specific technologies. Front-End: HTML, CSS, Bootstrap, React.js Back-End: Django(Python) Even if I'm pretty familiar with HTML/CSS, others languages/frameworks are totally new to me. I have a hard time to understand how these tech are organized, which to implement first and how to deal with the backend. I won't be working alone on this project and I will basically do the front-end part but I'm a bit lost. I've done some research but I cannot find anything related to how these tech are organized. I know that, of course, we will implement HTML/CSS/Boostrap first but then, in which case do you use javascript, how do you generate pages etc...? In my project, we have to build a company website with a solid database where we can store specific articles that users will be allowed to comment etc. We also have to implement a user interface, an admin interface, a payment plugin etc... I just don't know how to proceed. Do I have to finish the … -
Can we use angular 2 with django(with out using django rest framework)?
Basically I am in a middle of a project, I am done with models and basic request. I wanted to use angular for front end but seems like integarting angular directly with django is a tough task. Can i use django directly if i return JsonResponse instead og=f HttpResponse or will it cause some trouble. -
Access specific object in a Django's class using ListView
In using a ListView in a Django's class, it is possible to access a specific object? Suppose I have three classes : The first class Perception(xwf_models.WorkflowEnabled, TimeStampedModel): loan = models.ForeignKey('loans.Loan') state = xwf_models.StateField(PerceptionWorkflow) start_date = models.DateField(_('Start date')) end_date = models.DateField(_('End date'), blank=True, null=True) current_balance = models.DecimalField(_('Current balance'), default=0, decimal_places=2, max_digits=11) operation_error = models.SmallIntegerField(_('Operation error'), default=0) notes = GenericRelation(Note) the second class PerceptionIndexView(StaffRestrictedMixin, FrontendListView): page_title = _('Perception') model = Perception template_name = 'loanwolf/perception/index.html' pjax_template_name = 'loanwolf/perception/index.pjax.html' row_actions_template_name = 'loanwolf/perception/list-actions.inc.html' url_namespace = 'perception' and the third class CustomerPerceptionIndexView(CustomerMixin, PerceptionIndexView): template_name = 'loanwolf/customers/perceptions.html' pjax_template_name = 'loanwolf/customers/perceptions.pjax.html' def get_context_data(self, **kwargs): context = super(CustomerPerceptionIndexView, self).get_context_data(**kwargs) filter_perceptions= (Perception.objects.filter(loan__request__customer__pk=self.customer.pk)) resultant = [r for r in context['results'] if r['object'] in filter_perceptions] context["resultant"] = resultant context["state"] = Perception.state #This has not solved my problem return context In the class Perception, I have already several perceptions instantiated. I would like to get access a specific instance of this class in CustomerPerceptionIndexView, but I am not able to do such thing. -
Integrating elasticsearch connection pooling in Django
I have a django application that stores status info of lots of sensors and I'm trying to use elasticsearch to store all of the status data, for further analysis. I have used elasticsearch a lot in Python scripts in general. My question is how to integrate elasticsearch-py/elasticsearch-dsl connection pooling into a django application. I would like to not create a connection for every request. I'm actually trying to embeed it into MyAppConfig inside apps.py but I'm not sure if it's a good idea. Any help? -
Celery TypeError on get_scheduler
Trying to setup Celery Running Django==1.10.2 and celery==4.0.2 with Supervisor but am getting this error on celery_beat Traceback (most recent call last): File "/home/user_one/venv/app_one/bin/celery", line 11, in <module> sys.exit(main()) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/__main__.py", line 14, in main _main() File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/celery.py", line 326, in main cmd.execute_from_commandline(argv) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/celery.py", line 488, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/base.py", line 281, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/celery.py", line 480, in handle_argv return self.execute(command, argv) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/celery.py", line 412, in execute ).run_from_argv(self.prog_name, argv[1:], command=argv[0]) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/base.py", line 285, in run_from_argv sys.argv if argv is None else argv, command) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/base.py", line 368, in handle_argv return self(*args, **options) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/base.py", line 244, in __call__ ret = self.run(*args, **kwargs) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/beat.py", line 107, in run return beat().run() File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/apps/beat.py", line 79, in run self.start_scheduler() File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/apps/beat.py", line 98, in start_scheduler print(self.banner(service)) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/apps/beat.py", line 120, in banner c.reset(self.startup_info(service))), File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/apps/beat.py", line 130, in startup_info scheduler = service.get_scheduler(lazy=True) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/beat.py", line 567, in get_scheduler lazy=lazy, TypeError: 'module' object is not callable app/settings.py BROKER_URL = 'redis://:{}@{}:{}/{}'.format(redis_pass, redis_host, redis_port, redis_db) CELERY_RESULT_BACKEND = 'redis://:{}@{}:{}/{}'.format(redis_pass, redis_host, redis_port, redis_celery_results_db) CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' I've used Celery successfully in other projects before but not with Django but I've followed the … -
Dynamic table creation with django
i am currently working on a DJANGO project and it happens that i need to generate a dynamic table in my template containing data from my models. The page contains some buttons (modify, delete, show full details) and the table itself my problem is i want to link the rows with the buttons such as when i click a button i can detect which row is selected then do the appropriate action (such as modifying the data or deleting it from the database) how can i do that -
elasticsearch python TransportError 404
It's hard to put this in a visible form, but I am making a request to the standard localhost:9200 from python using the API. The first test is made from Django using the development server running on 0.0.0.0:8000. This returns fine. The second is done from Django through uWSGI and nginx. It returns: TransportError(404, u'{"_index":"xxx","_type":"xxx","_id":"xxx","found":false}') For the exact same request. Both are pointing to localhost:9200. It doesn't make sense to me that the development server has some special privilege. It is definitely connecting because: A) I display a list of results first, then detail for each item. The list displays and shows all the results fine in both cases, but the detail view fails. B) It is a TransportError, not a ConnectionError, meaning that it searched and returned no results, unless I am wrong. Thanks in advance. -
How to remove label?
How to remove label from MultipleChoiceField in template? forms.py: class RequirementAddForm(forms.ModelForm): symbol = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=REQUIREMENTS_CHOICES,) class Meta: model = Requirement fields = ('symbol',) template.html: {{ form }} -
How to install libmaxminddb on heroku
The libmaxminddb improves the performance of geo location look ups. But how can I install it on heroku? -
'django.template.context_processors.request' issue with django-tables2 and django-admin-tools
I'm having an issue when trying to render a PDF through xhtml2pdf in Django(1.10.4) when using django-admin-tools(0.8.0) & django-tables2(1.5) together. I've done enough reading to understand the basis of what's going on but have not idea how to fix it. I think it's got something to do with the django-admin-tools custom loaders. Link to the exception I'm getting from django-tables. This SO question led me to asking a question. The gist of what I'm trying to do is create a custom Admin 'action' through the drop-down box of my AdminModel in the django-admin interface that turns the queryset given into a PDF document. According to the django-tables2 docs the render() function takes 3 arguments (request, 'template_name.html', {'people': Person.objects.all()}). So I added a queryset to my context_dict and tried using it in a for loop in the template below but no dice. The template renders the html to pdf just fine without django-tables2 but if I try to convert the tables to PDF I get the following... Traceback Environment: Request Method: POST Request URL: http://127.0.0.1:9999/admin/research/labsample/ Django Version: 1.10.4 Python Version: 3.5.2 Installed Applications: ('admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_tables2', 'import_export', 'chemicals', 'suppliers', 'customers', 'recipes', 'research') Installed … -
Django oscar paypal not working
so I am trying to set up django-oscar-paypal with django-oscar. So, everything works fine, the paypal express checkout page shows correctly, then it redirects back to the store and when i click the place order button, it redirects to an empty basket, with no transaction being recorded in the dashboard, except for the express dashboard, which shows success. My guess is there is a session loss, or I need to edit the checkout view somehow for it to post the request, but i can't find anywhere on how to do that, and copying the one from the sandbox isn't helpful. If anybody managed to make it work I would be very grateful for help. -
Django formset UpdateView won't let me upload files
I'm trying to create an UpdateView view with multiple inline formsets. It's working almost fine as I can add or remove files and images, but for some reason it won't accept any file/image. For example, if I add a second File in a Publication and upload a file, it will return a form_invalid function stating that This field is required next to the FileField. Same thing with images - I can't add any new image or I can't even change any image to another file as it'll say that this field is required. Other than that, I can change all the Publication fields and I can also change File's title, description and version and it'll save properly, but when I add a new File/Image or just change the file it uses, then it won't do anything and it'll just return an invalid form function. #models.py class Publication(models.Model): title = models.CharField('Tytul', max_length=100) author = models.ForeignKey(User, verbose_name=('Author'), blank=True, default=0) pub_date = models.DateTimeField('Data publikacji', default=datetime.now) mod_date = models.DateTimeField('Data ostatniej modyfikacji', default=datetime.now) description = models.CharField('Opis', max_length=450) slug = models.SlugField(max_length=40, unique=True) category = models.ForeignKey(Category, verbose_name=('Kategoria'), default=0, related_name='publication') video = EmbedVideoField(blank=True) class File(models.Model): title = models.CharField('Tytul', max_length=100) version = models.CharField(verbose_name=u"Wersja", max_length=100) author = models.ForeignKey(User, verbose_name=('Author'), blank=True, … -
Querying the Sqlite database for a user with username "x" using the standard django.contrib.auth.models.User model
I'm trying to wrap my head around an issue I'm having. I want to present the users with a page in which they can look up a user by entering his username. Yet I can't wrap my head around how to do this. Do I provide a function in my view in which a query is executed that retrieves a user from the database? For example retrieve his username or id and go to his profile page? I can't seem to grasp how to do this, I have been looking for examples on this but I can't find anything so I hope someone here can help me out!