Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to customize fields in django rest framework serializer
I want to create a new record in database, I set a model like below: class FooModel(models.Model) subject_key= models.CharField(max_length=2) subject= modeels.CharField(max_length=100) What I want to do is this: field 'subject_key' should be given by the client, and using the subject_key, the server will find value 'subject' and put it in the database. So I tried to use ModelSerializer to create a new record. class FooSerializer(serializers.ModelSerializer): class Meta: model = FooModel def get_subject(self, obj): if obj.subject == 'SO': return 'Stack Overflow' else: return 'Nothing in here' and main running code inside view rest api is: def create(self, request, *args, **kwargs): serializer = FooSerializer(data=request.data) if serializer.is_valid(raise_exception=True) serializer.save() foo = serializer.data I checked it successfully create a new record in database, but the new record has NULL with the column 'subject' What should I do to dynamically set the field value inside serializer? -
class based view attributes
is it necessary to fill-in fields while having form_class for form.is_valid to work? because it ain't saving. class MedicalCreateView(CreateView): template_name = 'patient/medical_create.html' model = MedicalHistory form_class = MedicalForm def get(self, request, pk): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request, pk): form = forms.MedicalForm .form_class(request.POST) if form.is_valid(): client = form.save(commit=False) # cleaned normalize data physician_name = form.cleaned_data['physician_name'] physician_address = form.cleaned_data['physician_address'] client.save() return redirect('index') -
Is there anything else I can do to this for better performance?
Am trying to write an API using Django Rest Framework, which many applications will look up to, but I think what I have done is not robust enough for Production. Coming from a Ruby environment, its advisable to add indexes to db in few cases so as not to have a very slow response. Running around to see if am on the right track, I can across this link and I felt this could be better refactored. Is there anything I can do to this to make is production worth it? Am as new as new in Python/Django. models.py from django.db import models class Cleaners(models.Model): created = models.DateTimeField(auto_now=True) firstName = models.CharField(max_length=50) lastName = models.CharField(max_length=50) location = models.CharField(max_length=50) address = models.CharField(max_length=100) bankName = models.CharField(max_length=100,default='zenith') bvn = models.IntegerField(null=True) verificationStatus = models.BooleanField(default=False) image = models.ImageField(upload_to='uploads/',height_field=50, width_field=50, max_length=100) phone = models.CharField(max_length=11,primary_key=True) class Meta: ordering = ('created',) class CleanersWork(models.Model): created = models.DateTimeField(auto_now_add=True) cleanerId = models.ForeignKey('Cleaners', on_delete=models.CASCADE) ratings = models.IntegerField() availability = models.BooleanField(default=True) jobHistory = models.IntegerField() currentEarning = models.DecimalField(max_digits=7,decimal_places=2) class Meta: ordering = ('created',) class Client(models.Model): created = models.DateTimeField(auto_now_add=True) firstName = models.CharField(max_length=50) lastName = models.CharField(max_length=50) address = models.CharField(max_length=100) verificationStatus = models.BooleanField(default=True) bvn = models.IntegerField(null=True) bankName = models.CharField(max_length=100,default='') image = models.ImageField(upload_to='uploads/',height_field=50,width_field=50,max_length=100) phone = models.CharField(max_length=11,primary_key=True) class Meta: ordering … -
How to get a video snapshot (thumbnail) of a video being uploaded?
There seems to be a large variety of answers, and a lot of outdated packages so some direction would be nice. What's the best way to go about it? Here's my code: models class Post(models.Model): ... image = models.FileField(null=True, blank=True) video = models.BooleanField(default=False) views if instance.image: f = instance.image.read(1024) file_type = magic.from_buffer(f, mime=True) if file_type == 'video/mp4': instance.video = True template {% if instance.video %} <video width="400" height="420" controls> <source src="{{instance.image.url}}" type="video/mp4"> <source src="{{instance.image.url}}" type="video/ogg"> Your browser does not support the video tag. </video> {% else %} {% if instance.image %} <img src="{{instance.image.url}}"> {% else %} <img src="{% static 'images/symbol.png' %}"> {% endif %} {% endif %} -
Access model instance in generic.DetailView
Is there a way to access the model instance that is going to be presented in a generic.DetailView in views.py before the template gets rendered? Something like the hypothetical function here: class MyModelDetailView(LoginRequiredMixin, generic.DetailView): model = MyModel template_name_suffix = '_details' def do_some_initial_stuff(model_instance): # do stuff to model_instace, # like assigning fields, creating context variables based on existing fields, etc. Ultimately, I would like have a user click a button for a specific model instance in one template, then get directed to this generic.DetailView template where the model is presented with some of its field values changed and some other stuff (eg. the model may have a field that acknowledges that the this user clicked the button in the previous template). Suggestions on the most efficient way to do this would be appreciated. Thanks :) -
Obtaining DRF-jwt token
Currently I am generating tokens manually, but I want to to use jwt tokens, I followed the official docs and other references but I am still unable to figure out the problem. serializers.py, in which after authenticating token is generated manually. class UserLoginSerializer(serializers.ModelSerializer): token = serializers.CharField(allow_blank=True, read_only=True) class Meta: model = User fields = [ 'username', 'password', 'token', ] extra_kwargs = {"password": {"write_only": True} } def validate(self, data): username = data.get('username', None) password = data.get('password', None) try: usern = Account.objects.get(username=username) except ObjectDoesNotExist: raise serializers.ValidationError("User does not exists") if usern.check_password(password): data["token"] = "asdasdasdasd" else: raise serializers.ValidationError("password invalid") return data urls.py from django.conf.urls import url from .views import AuthRegister, AuthLogin from rest_framework_jwt.views import obtain_jwt_token urlpatterns = [ url(r'^register/$', AuthRegister.as_view()), url(r'^login/$', AuthLogin.as_view()), url(r'^api-token-auth/', obtain_jwt_token), ] In settings I have included 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', I have used url(r'^api-token-auth/', obtain_jwt_token), but I am unable to figure out how will I generate jwt tokens. Please anyone help me out! -
Django - Almost all tests failing with the same error (NoReverseMatch)
I used to contribute to a django project, https://github.com/Cloud-CV/evalai and everything used to work fine. After doing a fresh install of XUbuntu 16.04, I tried to configure the project again. This time all commands work fine, except while I run the test suite. python manage.py test --settings=settings.dev Out of 283 tests 236 tests failed with the similar error message but the development server is working fine. This is one of the test which failed def test_unstar_challenge(self): self.url = reverse_lazy('challenges:star_challenge', kwargs={'challenge_pk': self.challenge.pk}) self.star_challenge.is_starred = False expected = { 'user': self.user.pk, 'challenge': self.challenge.pk, 'count': 0, 'is_starred': self.star_challenge.is_starred, } response = self.client.post(self.url, {}) self.assertEqual(response.data, expected) self.assertEqual(response.status_code, status.HTTP_200_OK) This is its error message. . . . . ====================================================================== ERROR: test_particular_challenge_update_with_no_data (tests.unit.challenges.test_views.UpdateParticularChallengePhase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/jeff/evalai/tests/unit/challenges/test_views.py", line 1320, in test_particular_challenge_update_with_no_data response = self.client.put(self.url, self.data) File "/home/jeff/evalai/venv/local/lib/python2.7/site-packages/rest_framework/test.py", line 298, in put path, data=data, format=format, content_type=content_type, **extra) File "/home/jeff/evalai/venv/local/lib/python2.7/site-packages/rest_framework/test.py", line 216, in put return self.generic('PUT', path, data, content_type, **extra) File "/home/jeff/evalai/venv/local/lib/python2.7/site-packages/django/test/client.py", line 409, in generic return self.request(**r) File "/home/jeff/evalai/venv/local/lib/python2.7/site-packages/rest_framework/test.py", line 279, in request return super(APIClient, self).request(**kwargs) File "/home/jeff/evalai/venv/local/lib/python2.7/site-packages/rest_framework/test.py", line 231, in request request = super(APIRequestFactory, self).request(**kwargs) File "/home/jeff/evalai/venv/local/lib/python2.7/site-packages/django/test/client.py", line 476, in request response = self.handler(environ) File "/home/jeff/evalai/venv/local/lib/python2.7/site-packages/django/test/client.py", line 129, in __call__ self.load_middleware() File … -
Django GUnicorn in production is calling setup.php
I was checking my logs with supervisor and I got this Not Found: /phpmyadmin/scripts/setup.php WARNING:django.request:Not Found: /phpmyadmin/scripts/setup.php does someone know why this is trying to reach a php file? I'm running django 11.06 with gninx and gunicorn. Thanks -
Querying the Database: Django
Here's my code, question = Question.objects.annotate(ans_count=Count('answer')).filter(ans_count=True).order_by('-answer').distinct() I'm filtering the Questions which received answers most recently! I'm using "sqlite3". .distinct() is not working and it's repeating the questions, means if a question gets 2 answers suddenly it will appear twice in the feed. How can I prevent one question from appearing multiple times in the feed? Thank You :) -
Chosen jQuery Plugin Only Shows a Broken List
Here is my code: <div id="div_id_code" class="form-group"> <label for="id_code" class="form-control-label requiredField"> Language<span class="asteriskField">*</span> </label> <div class=""> <select class="select form-control" id="id_code" name="code" required> <option value="" selected="selected">---------</option> <option value="en">Inglés</option> <option value="zh-hans">Chino simplificado</option> <option value="zh-hant">Chino tradicional</option> <option value="es">Español</option> <option value="hi">Hindi</option> <option value="ar">Árabe</option> <option value="pt-br">Portugués de Brasil</option> ... ... </select> </div> </div> </div> ... ... <script src="{% static 'js/jquery.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/chosen.jquery.min.js' %}"></script> <script type="text/javascript"> $( document ).ready(function() { $('#id_code').chosen(); $('#id_fluency').chosen({disable_search_threshold: 10}); }); </script> When chosen() is not called, the page shows the default select widget. Otherwise it shows a broken list as below: Am I doing anything wrong here? Thank you. -
Django or conventional PHP?
Currently, I am the president and the code head of my school's IT club. The thing is, I made a website for club (which is yet to be surfaced online). I used basic HTML, CSS, JS and PHP. For now, I got the website running on Apache localhost with phpmyadmin. The dilemma I'm facing is, should I use Django instead? For now, I can code really well in Python, but have no experience in Django. The specifications of the website are: The website has a registration page using which school admins can register students for the IT fest that we are organizing. The website has an 'Events' page where all the events we have conducted or will conduct will be displayed. This info will be stored and retrieved from the database. For now I got my Events page to work by implementing a PHP loop for creating divs. The homepage has some good looking CSS and JS scroll animations. This definitely is a small scale website (don't get me wrong, complete website has not been described above). The trouble is, no one seems to take interest in coding or event organizing or anything that our group stands for. I have … -
Django 1.9 can't pass data from filled form to view
I have the form: class ContactUsForm(forms.Form): name = forms.CharField(label='Your name') phone = forms.CharField(label='Your phone') email = forms.CharField(label='Your email') and this is html code of the form: <form action="/contact_us/" method="POST"> {% csrf_token %} {{contact_us.non_field_errors}} {{contact_us.errors}} {{contact_us}} <input type="submit" class="button large" value="Submit"> </form> this form should send the data on email, so this is my view: def contact_us(request): if request.POST: contact_us = ContactUsForm(request.POST) if contact_us.is_valid(): name = contact_us.cleaned_data['name'] phone = contact_us.cleaned_data['phone'] mail = contact_us.cleaned_data['email'] message = "Name: " + name + "Phone: " + phone + "Email" + mail send_mail('Contact Us Form', message, settings.EMAIL_HOST_USER, ['my@email.com']) return HttpResponseRedirect('/thanks/') else: return render (request, 'article/index.html', {'contact_us':contact_us}) else: contact_us = ContactUsForm() return render(request, 'article/index.html', {'contact_us':contact_us}) when i fill the form i got en error that all fields are required. But all the fields there was filled. when i add required=False to every field of the form, then i receive email with empty fields. I don't know whats wrong with my form. Can you help me with that. Thanks a lot UPD: this is how look like url: url(r'^contact_us/', contact_us, name='contact_us'), -
Sphinx-apidoc strange output for django app/models.py
I get some missed info in generated documentation of django project, for example first_name and last_name, email are missed (although they are defined in a parent abstract class). How to control what gets added into documentation based on sphinx-apidoc scan? My goal is to auto-generate the docs based on documentation, but it seems that sphinx-apidoc is supposed to be used only one time for initial scaffolding I execute the following command sphinx-apidoc -f -e -d 2 -M -o docs/code apps '*tests*' '*migrations*' Output my apps/users/models.py from django.contrib.auth.models import AbstractUser from django.contrib.postgres.fields import HStoreField from imagekit import models as imagekitmodels from imagekit.processors import ResizeToFill from libs import utils # Solution to avoid unique_together for email AbstractUser._meta.get_field('email')._unique = True def upload_user_media_to(instance, filename): """Upload media files to this folder""" return '{}/{}/{}'.format(instance.__class__.__name__.lower(), instance.id, utils.get_random_filename(filename)) __all__ = ['AppUser'] class AppUser(AbstractUser): """Custom user model. Attributes: avatar (file): user's avatar, cropeed to fill 300x300 px notifications (dict): settings for notifications to user """ avatar = imagekitmodels.ProcessedImageField( upload_to=upload_user_media_to, processors=[ResizeToFill(300, 300)], format='PNG', options={'quality': 100}, editable=False, null=True, blank=False) notifications = HStoreField(null=True) # so authentication happens by email instead of username # and username becomes sort of nick USERNAME_FIELD = 'email' # Make sure to exclude email from required fields if … -
Difference between installing by pip and installing globally
I am workikng with Python/Django web application, in Amazon EC2 / Debian series operating system. Application has Python setuptools library as dependency. So I installed setup this lib by this command globally: sudo apt-get install setuptools But this didn't work - application says dependency didn't resolved correctly. After some googling, I have found solution, like this: pip install setuptools. This worked for me. But I have a question - what's difference between these two? Of course, I didn't activated virtualenv, so it seems setuptools is installed globally. Would you like to bring me your experience? Please help me. -
How to insert data instance from view in django?
I have a problem to insert instance data in django, this is my model class DipPegawai(models.Model): PegID = models.AutoField(primary_key=True) PegNamaLengkap = models.CharField(max_length=100, blank=True, null=True) PegUser = models.OneToOneField(User, null=True, blank=True, unique=True) class DipHonorKegiatanPeg(models.Model): KegID = models.AutoField(primary_key=True) PegID = models.ForeignKey(DipPegawai) this is my view def tambah_klaimhonor(request): klaim = {} user = request.user.id honoruser = DipHonorKegiatanPeg(DipPegawai) if request.method == 'POST': form = KlaimHonorGuruKarForm(request.POST, instance=honoruser) if form.is_valid(): form.save() # form.save() return redirect('index_klaimhonor') klaim['form'] = KlaimHonorGuruKarForm() return redirect('index_klaimhonor') when i insert data, i get this error Traceback: 23. return view_func(request, *args, **kwargs) File "C:\Users\Lenovo\OneDrive\sisgaji\honorkegiatanpeg\views.py" in tambah_klaimhonor 120. form.save() File "C:\Users\Lenovo\hrd\lib\site-packages\django\forms\models.py" in save 451. self.instance.save() File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\base.py" in save 700. force_update=force_update, update_fields=update_fields) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\base.py" in save_base 728. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\base.py" in _save_table 793. forced_update) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\base.py" in _do_update 823. filtered = base_qs.filter(pk=pk_val) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\query.py" in filter 790. return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\query.py" in _filter_or_exclude 808. clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\sql\query.py" in add_q 1243. clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\sql\query.py" in _add_q 1269. allow_joins=allow_joins, split_subq=split_subq, File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\sql\query.py" in build_filter 1203. condition = self.build_lookup(lookups, col, value) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\sql\query.py" in build_lookup 1099. return final_lookup(lhs, rhs) File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\lookups.py" in __init__ 19. self.rhs = self.get_prep_lookup() File "C:\Users\Lenovo\hrd\lib\site-packages\django\db\models\lookups.py" in get_prep_lookup 57. return self.lhs.output_field.get_prep_lookup(self.lookup_name, self.rhs) … -
dynamic form template based on the field type
I am doing the django project right now. I love the principle of DRY. I have a form which can be applied to all other pages which needs it. I mean a generic form based from django docs. But in the form, there can be select type, file upload, checkbox, radio etc which I dont like the design of native html. I want to leverage the design of material with some customization. I want it be done in template not from the forms.py. How can I do it? Below is my form and my form has checkbox, file upload and multiple select which I need to customize. In a nutshell, my question is how do I make my generic form designer friendly? form.html <form class="form" role="form" action="" method="post" enctype='multipart/form-data'> {% csrf_token %} {% for field in form %} {% if field.errors %} <div class="form-group label-floating has-error"> <label class="control-label" for="id_{{ field.name }}">{{ field.label }}</label> <div class="col-sm-10"> {{ field|add_css:'form-control' }} <span class="help-block"> {% for error in field.errors %}{{ error }}{% endfor %} </span> </div> </div> {% else %} <div class="form-group label-floating"> <label class="control-label" for="id_{{ field.name }}">{{ field.label }}</label> {{ field|add_css:'form-control' }} {% if field.help_text %} <p class="help-block"><small>{{ field.help_text }}</small></p> {% endif %} … -
Django Avoid Data Repetition
Here's my code, question = Question.objects.annotate(ans_count=Count('answer')).filter(ans_count=True).order_by('-answer').distinct() I'm using "sqlite3". .distinct() is not working since it's repeating the questions. This way if a question gets 2 answers suddenly it will appear twice in the feed. How can I restrict it from appearing multiple times in the feed? Thank You :) -
Django html template will not display database variables
I am new to django and am having trouble getting database items to display on my website using a html template. I have made sure that the queryset for the database exists and has items in it, and I can display text on the home page fine as long as the template does not have any variables. Currently my home page displays only the Title and the rest is blank. Python 3.5, django 1.11, sqlite3. models.py: from django.db import models from django.utils import timezone from django.contrib import admin class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() image = models.ImageField(upload_to= 'static/media/', default = 'static/media/Firefox_wallpaper.png') created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title views.py: from django.shortcuts import render from .models import Post from django.utils import timezone def post_list(request): posts=Post.objects.filter(published_date__lte=timezone.now()) .order_by('published_date') return render(request, 'main/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'main/post_detail.html', {'post': post}) base.html: {% load staticfiles %} <html> <head> <title>Title</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> </head> <body> <div class="page-header"> <h1><a href="/">Title</a></h1> </div> <div class="content container"> <div class="row"> <div class="col-md-8"> {% block content … -
apache(cpanel) + mod_wsgi + Python3 + Service Temporarily Unavailable
Goodnight everyone. I'm trying to do the deployment of an application developed with django in a VPS. This VPS has installed centos 6.8. Apache is configured through the cpanel. After installing python3 and wsgi proceeded to configure the icnlude of the virtual host, which was as follows: <ifmodule mod_wsgi.c> WSGIDaemonProcess pruebas.caso.org python-path=/home/admin/pruebas.org/envSpf/spf:/home/admin/pruebas.org/envSpf/lib/python3.5/site-packages/ WSGIProcessGroup pruebas.caso.org WSGIScriptAlias / /home/admin/pruebas.org/envSpf/spf/spf/wsgi.py </ifmodule> Alias /static "/home/admin/pruebas.or/envSpf/spf/static/" <Directory /home/admin/pruebas.or/envSpf/spf/static> Require all granted </Directory> Alias /media "/home/admin/pruebas.or/envSpf/spf/media/" <Directory /home/admin/pruebas.or/envSpf/spf/media> Require all granted </Directory> <Directory /home/admin/pruebas.or/envSpf/spf/spf> <Files wsgi.py> Require all granted </Files> </Directory> With this configuration at the moment the server gives me the following response in the browser request: Service Temporarily Unavailable The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later. Additionally, a 503 Service Temporarily Unavailable error was encountered while trying to use an ErrorDocument to handle the request. The VPS provider is not very helpful and the error log refers to another domain (?? !!!). I would appreciate any guidance that could help me resolve this inconvenience. -
Update first_date and last_date to counting customers per period
In my django project, it is possible to show every customer in the application with CustomerProfile.objects.all() and find the creation date of a specific customer with In [12]: cust = CustomerProfile.objects.get(pk=100) In [13]: cust.user.date_joined Out[13]: datetime.datetime(2017, 7, 28, 14, 43, 51, 925548) In [14]: cust Out[14]: <CustomerProfile: FistName LastName's customer profile> According to the creation date, I would like to make a listing of how many customers has been created per day, week, month or year. An example of the result could be ... week 28 : [ 09/07/2017 - 15/07/2017 ] - Count : 201 customers ... I probably need a range start_date and end_date where we will list that kind of information. start_date will be the date of the first customer created and the start_week created would be the week of this first_date. Obviously, the end_date is the date of the last customer created and last_week is the week of this end_date. For instance, if I select Per week in the drop-down menu and press Apply in the form, I want to send information to my model in such I could code what I explained. So far I know how to count the number of client in a … -
Django Rest Framework or JsonResponse
I want to make my current more interactive by having ajax that calls for json data, I haven't done anything yet except for research and studying. Here are some things I am not very clear. If JsonResponse and DRF can give the json data i need how is DRF different from JsonResponse ? -
Django, Querying the Database
Here's my model, class Question(models.Model): .... class Answer(models.Model): question = models.ForeignKey(Question) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) I wants to filter out the questions which received maximum answers in last 24 hours. How can I do that? Thank You :) -
bijectivity between the view and the model
I am a new programmer in Django/Python, and I need your help. Here what I got so far : views.py class StatisticsIndexView(StaffRestrictedMixin, TemplateView): model = Statistics() template_name = 'loanwolf/statistics/index.html' form_class = StatisticsBaseForm() def get_context_data(self, **kwargs): context = super(StatisticsIndexView, self).get_context_data(**kwargs) context.update({ 'applications_by_state': ApplicationsByState(), 'applications_calendar': ApplicationsCalendar(), 'new_customers_calendar': NewCustomersCalendar(), 'statistics': Statistics(), 'form': StatisticsBaseForm(), }) return context models.py class Statistics(TimeStampedModel): def nb_of_customers_per_period(self): return CustomerProfile.objects.filter(user__date_joined__range=["2017-09-03", "2017-09-09"]) From my view model, I know that <QueryDict: {u'from_regular_product': [u'1'], u'product_type': [u'regular'], u'period': [u'week'], u'from_special_product': [u''], u'apply': [u'Apply'], u'type_choice': [u'0'], u'debit_frequency': [u'1month']}> You have to know that u'period' has exactly for choices, i.e., day, week, month and year. In my django project, it is possible to show every customer in the application with CustomerProfile.objects.all() and find the creation date of a specific customer with In [12]: cust = CustomerProfile.objects.get(pk=100) In [13]: cust.user.date_joined Out[13]: datetime.datetime(2017, 7, 28, 14, 43, 51, 925548) In [14]: cust Out[14]: <CustomerProfile: FistName LastName's customer profile> Question: Here is my problem. I would like to consider the value of u'period' from self.request.GET inside my model. How to communicate the result from my view inside my model (clear??). The purpose is to tell how many customers has been created in the current period. In pseudocode, this gave … -
passing JavaScript variable to Django
How can I pass a js variable to Django? I have this simple code: $(".update_btn").click(function() { var row_id=$(this).attr("row_id") I want to pass row_id as index to a Django parameter called ticket_row, so that I could have ticket_row[row_id][1] I started to pass the first index with console.log("{{ ticket_row['" + row_id + "'] }}") but it's working correctly. So, I need some help here :) Any one has any suggestion / solution? Thanks! -
Why I'm unable to create core 'blog' in Solr 4.10.4?
I'm trying to integrate Apache Solr with my Django blog application. I'm using Apache Solr 4.10.4 downloaded from https://archive.apache.org/dist/lucene/solr/4.10.4/. I started Solr in terminal by typing java -jar start.jar in terminal as normal user. I tried create a new core with following parameters: name: blog instanceDir: blog dataDir: data config: solrconfig.xml schema: schema.xml But I'm getting error while creating core: Error CREATEing SolrCore 'blog': Unable to create core [blog] Caused by: null Also below error occures when initalization: SolrCore Initialization Failures blog: org.apache.solr.common.SolrException:org.apache.solr.common.SolrException Please check your logs for more information Directory structure in ~/Downloads/solr-4.10.4/example/solr/blog: pecan@tux ~/Downloads/solr-4.10.4/example/solr $ tree blog blog ├── conf │ ├── lang │ │ └── stopwords_en.txt │ ├── protwords.txt │ ├── schema.xml │ ├── solrconfig.xml │ ├── stopwords.txt │ └── synonyms.txt ├── data │ └── index │ ├── segments_1 │ ├── segments.gen │ └── write.lock ├── nfa_regexp_debug.log ├── nfa_regexp_dump.log └── nfa_regexp_run.log 4 directories, 12 files Could anybody tell me what I'm doing wrong?