Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OneToOneField is not working django
I have create OneToOneField relation in model and want to get data related data Here is my model code class Login (models.Model): login_id = models.AutoField(primary_key = True) user_name = models.CharField(max_length = 150) password = models.CharField(max_length = 255) role_id = models.IntegerField() user_id = models.IntegerField(unique = True) class Meta: db_table = 'login' def __str__(self): return self.login_id class Catcher(models.Model): catcher_id = models.OneToOneField('Login', to_field = 'user_id', primary_key = True) catcher_fname = models.CharField(max_length = 128, blank = True) catcher_lname = models.CharField(max_length = 128, blank = True) api_key = models.CharField(max_length = 100, blank = False) class Meta: db_table = 'catcher' def __str__(self): return self.catcher_id I have Login table and login_id is PK, 2 table is Catcher and catcher_id is PK key. In Login table user_id is FK and that is related to Catcher_id(PK) in catcher table. When i run a query on catcher table without relation it's return me table data catcher_id = models.AutoField(primary_key = True) Query loginDetail = Catcher.objects.get(catcher_id =742 ) # Runing succssfully But when i create a relation it return an error catcher_id = models.OneToOneField('Login', to_field = 'user_id', primary_key = True) loginDetail = Catcher.objects.get(catcher_id =742 ) # Get an error OperationalError at /login/login/ (1054, "Unknown column 'catcher.catcher_id_id' in 'field list'") why it return … -
How to create a queryset that filters multiple fields based on a single condition in Django?
My model is class TestModel(models.Model) field1 = models.IntegerField() field2 = models.IntegerField() field3 = models.IntegerField() field4 = models.IntegerField() field5 = models.IntegerField() I need a simple queryset that applies a single condition on all the five fields of the model without writing every combination of fields and filtering them. For example I want to apply a condition of checking for None to two or more fields TestModel.objects.filter(two_or_more_fields=None) I don't want write every possible combination of 5 fields to find the queryset with any two or more fields as None. In other words, is there a better way to accomplish this than: from django.db.models import Q TestModel.objects.filter( #condition for exactly 2 None Q(field1=None & field2=None) | Q(field2=None & field3=None) | Q(field3=None & field4=None) | Q(field4=None & field5=None) | Q(field5=None & field1=None) | #condition for more than 2 None Q(field1=None & field2=None & field3 = None) | ''''' . . #so on to cover all possible cases of any two or more fields as None ) I think there should be a better and simple way to accomplish this. -
Open the pdf file with Django
I'm having trouble to open a pdf file with PyPDF2 in Django. The code tree is as follows: And inside views_member I have function as follows: @login_required def export_to_pdf(request, user_id): existing_pdf = PdfFileReader(open('files/file.pdf', "rb")) print("document1.pdf has %d pages." % existing_pdf.getNumPages()) But when I run this function I get an error: [Errno 2] No such file or directory: 'files/file.pdf' Any advice? -
is it possible to install django on remote server with sftp only
I receieved from client sftp only login from server and he can't give me ssh access because his programmer is on vacation for sometime. But I need to deploy my application Is it possible to install django with sftp only? -
'NoneType' object has no attribute 'number_records'
This is my forms: class HistoryForm(UserSensitiveForm): number_records = forms.CharField(disabled=True,widget=Label()) percentage_of_records = forms.CharField(disabled=True, widget=Label()) class Meta: model = History fields = ['number_records','percentage_of_records'] disabled_fields = ['number_records', 'percentage_of_records'] def __init__(self, *args, **kwargs): super(HistoryForm, self).__init__(*args, **kwargs) self.fields['percentage_of_records'] = forms.CharField(initial=self.instance.percentage_of_records, widget=Label(), disabled=True) This is my models: class History(models.Model): """The base model for history that are run""" user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) rule = models.ForeignKey("Rule", on_delete=models.SET_NULL, null=True) job = models.ForeignKey("Job", on_delete=models.SET_NULL, null=True) number_records = models.IntegerField(null=True, default=0) @property def percentage_of_records(self): percentage_of_records = History.objects.filter(job=self.job).aggregate(Sum('number_records'))['number_records__sum'] return '{0:.2f}%'.format(percentage_of_records/self.job.number_records) While run at UI getting above error.Any body can help in this. And i have above in forms if self.instance is not None: but it's still showing above error. i think, there generating none only. -
Creating fixture with block format instead of inline format in django
I am using pyyaml. I'm using following command to create fixtures in django project: python manage.py dumpdata app.ModelName --format=yaml > fixtures/dev/fixture_name.yaml What I get as output is: - fields: {active: true, created_at: !!timestamp '2016-11-14 10:43:40.221602', age: 54, updated_at: !!timestamp '2016-11-14 10:43:40.221603', user_type: 1} model: app.ModelName pk: 1 What I want is: - fields: created_at: 2016-11-14 10:43:40.220895 age: 54 user_type: 1 updated_at: 2016-11-14 10:43:40.220900 model: app.ModelName pk: 1 How can I achieve this? -
Django-registraion [Errno 0] Error
I'm getting an [Errno 0] Error when trying to do a new registration with django-registration. The user is being saved to auth_user but no email etc is sent. Here's the traceback: Environment: Request Method: POST Request URL: http://www.kiddido.hexiawebservices.co.uk/accounts/register/ Django Version: 1.10.6 Python Version: 2.7.12 Installed Applications: ['klair', 'django.contrib.admin', 'registration', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'nocaptcha_recaptcha', 'ckeditor'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/var/www/klair/env/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/var/www/klair/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/var/www/klair/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/klair/env/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/var/www/klair/env/lib/python2.7/site-packages/registration/views.py" in dispatch 33. return super(RegistrationView, self).dispatch(*args, **kwargs) File "/var/www/klair/env/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/var/www/klair/env/lib/python2.7/site-packages/django/views/generic/edit.py" in post 183. return self.form_valid(form) File "/var/www/klair/env/lib/python2.7/site-packages/registration/views.py" in form_valid 36. new_user = self.register(form) File "/var/www/klair/env/lib/python2.7/site-packages/registration/backends/hmac/views.py" in register 36. new_user = self.create_inactive_user(form) File "/var/www/klair/env/lib/python2.7/site-packages/registration/backends/hmac/views.py" in create_inactive_user 55. self.send_activation_email(new_user) File "/var/www/klair/env/lib/python2.7/site-packages/registration/backends/hmac/views.py" in send_activation_email 98. user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL) File "/var/www/klair/env/lib/python2.7/site-packages/django/contrib/auth/models.py" in email_user 362. send_mail(subject, message, from_email, [self.email], **kwargs) File "/var/www/klair/env/lib/python2.7/site-packages/django/core/mail/__init__.py" in send_mail 62. return mail.send() File "/var/www/klair/env/lib/python2.7/site-packages/django/core/mail/message.py" in send 342. return self.get_connection(fail_silently).send_messages([self]) File "/var/www/klair/env/lib/python2.7/site-packages/django/core/mail/backends/smtp.py" in send_messages 100. new_conn_created = self.open() File "/var/www/klair/env/lib/python2.7/site-packages/django/core/mail/backends/smtp.py" in open 64. self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile) File "/usr/lib/python2.7/smtplib.py" in starttls … -
Python code failing to execute in Django app
In 'App1', I created 'Class1' in models.py. Works just fine. In 'App2', I created 'Class2' in myfile.py, which inherits from 'Class1'. Works just fine. In 'App3', I created 'Class3' in myfile.py, which inherits from 'Class1'. In spite of Class3 being identical to Class2 in all but name and location, the code fails to execute. I know this because I slipped in print statements into App2.myfile.py and App3.myfile.py and, while there was output from App2.myfile.py, there was no output from App3.myfile.py. Note that the myfile.py files are located in the root of their respective app. Trying to get to the bottom of the problem, created a new project, copied over App1, App2 and App3 and ran it again. This time there no output from either of the print statements at all and - big surprise - my application stopped working. 1) Why is myfile.py failing to execute? 2) How did I get Project1.App2.myfile.py to execute in the first place??? -
Django asyn call to Kafka topic
I need to log my all the request coming to django REST service. How can I make asynchronously call with the request data to the kafka log topic ? My asyn call act as a producer to the log topic ? Thanks. -
How to import mysql data into postgresql in Heroku?(Django project)
Recently I need to import mysql data into postgres database in Heroku. Actcually it includes several steps: convert mysql data to postgresql import postgresql data to Heroku After referring plenty of materials and testing several tools in github, finally I succeed. Here I want to share some of my experience and references. -
Inheritance for django model Translation
I have a django model class and I applied model translation on that class as described below. I applied translation for some of the model fields. Now if i inherit this model to another model class, then I can not get access to the fields of the parent class which are added into translation. why? class LayerTranslationOptions(TranslationOptions): fields = ( 'title', 'abstract', 'purpose', 'constraints_other', 'supplemental_information', 'data_quality_statement', ) translator.register(Layer, LayerTranslationOptions) -
How to display a ForeignKey field as a selection field in django template
I need to display a foreignKey field as a selection field in Django template, which will show all the available records as a dropdown. On considering the case of querying to database every time on selecting the field, which is the best method to achieve above goal to make a selection field from ForeignKey field. -
Django Content-Type : Checking if a field is declared as Many-to-Many field
I checking few field names passed by the APIs from the browser and validating them before passing to Django ORM queries. The question is for a given mode and given field name, how can I determine if the field is declared as Many-to-Many field using the Content-Type framework? -
Wagtail, ChoiceBlock update Textarea by "onchange" event handler within widget
I am trying to implement a code editing block which contains a ChoiceBlock and a TextBlock. I successfully added codemirror to textarea used as code editing panel. I am now struggling on adding event handler to ChoiceBlock that I would like to change mode of textarea by selecting the language in ChoiceBlock. I am trying adding javascript to the widget with the same way I did for code textarea. However, it does not work. I have checked the django documents. And it seems that I need to override some method in forms.Select and set it to widget within ChoiceBlock. But I have no idea how to implement it. blocks.py LANGUAGES = ( ('cpp', 'C++'), ('java', 'Java'), ('python','Python'), ('python3', 'Python 3'), ('bash', 'Bash/Shell'), ('html', 'HTML'), ) class CodeChoiceBlock(ChoiceBlock): @cached_property def field(self): field_kwargs = { 'widget': CodeSelectWidget(), } field_kwargs.update(self.field_options) return forms.ChoiceField(**field_kwargs) class CodeTextBlock(TextBlock): @cached_property def field(self): field_kwargs = { 'widget': CodeTextWidget(), } field_kwargs.update(self.field_options) return forms.CharField(**field_kwargs) class CodeBlock(StructBlock): #language = ChoiceBlock(choices=LANGUAGES, blank=False, null=False, default='python') language = CodeChoiceBlock(choices=LANGUAGES, blank=False, null=False, default='python') code = CodeTextBlock() def render(self, value): src = value['code'].strip('\n') lang = value['language'] lexer = get_lexer_by_name(lang) formatter = get_formatter_by_name( 'html', linenos=None, cssclass='codehilite', style='github', noclasses=False, ) return mark_safe(highlight(src, lexer, formatter)) class Meta: icon="code" widgets.py codemapper … -
Python: uswgi socket
Uwsgi is throwing internal server error when the socket is defined explicitly like socket = 127.0.0.1:5000 but working fine when using socket like this socket = /run/uwsgi/%(project).sock Nginx is used as the server. Can someone please tell the reason? -
The current date didn't show up
I am trying to load the current date in using the question How to format date in different languages?. However, the date didn't show up and I cannot say why. Here is text content {% load i18n %} {% load date %} {{ customer.civil_title }}{{ user.get_full_name }} {{ customer.civic_number }}, {{ customer.street }} {{ customer.rough_location }} {% language 'en' %} {{ item.date|date:'D, d N H:i:s e' }} {% endlanguage %} 7 DAYS NOTICE Subject: Overdue account with Credit 24 Client id : {{ customer.id }} Hello {{ customer.civil_title }}{{ user.get_full_name }}, This notice serves to inform you that your payments with Gestion Multi Finance Inc. are pending. Your file has been transferred to our collection service. The balance of your loan is now: {{ customer.current_balance }}. We are asking you to communicate with us without delay, by phone at: or by email at: to find a payment solution in order to regulate your situation. If this does not happen, we will be forced to send you a notice of acceleration of the process and transfer your file to our judiciary collection service, with authority to take the necessary steps in the collection process. These steps can include the seizure of … -
What's the purpose of ugettext_noop in Django?
As mentioned in this section of Translation | Django documentation, the function ugettext_noop is a utility function for internationalization: ugettext_noop(message) ¶ Marks strings for translation but doesn’t translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later. Also, this answer provides an example of its usage: import logging from django.http import HttpResponse from django.utils.translation import ugettext as _, ugettext_noop as _noop def view(request): msg = _noop("An error has occurred") logging.error(msg) return HttpResponse(_(msg)) Despite these docs, I still don't understand why should I mark a string as extractable for translation. To me it seems that ugettext_noop is nothing but a reminder, and even so, what's the purpose of reminding programmers that some strings (msg in this case) are to be translated later? -
Django Internationlization in Python2 not working (Unicode Decode Error)
I tried to implement Internationalize in Django I followed this tutorial here: https://medium.com/@nolanphillips/a-short-intro-to-translating-your-site-with-django-1-8-343ea839c89b But I got an UnicodeDecodeError like below whenever I executed “python manage.py makemessage -l en” command “UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe9 in position 1: ordinal not in range(128)” I also tried to change locale setting in both bashrc and environment files to: LANG=en_US.UTF-8 LANGUAGE=en_US:en LC_CTYPE="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_PAPER="en_US.UTF-8" LC_NAME="en_US.UTF-8" LC_ADDRESS="en_US.UTF-8" LC_TELEPHONE="en_US.UTF-8" LC_MEASUREMENT="en_US.UTF-8" LC_IDENTIFICATION="en_US.UTF-8" LC_ALL=en_US.UTF-8 But no luck, the error still there Any idea? Thank you -
Adapt css style from a website to a Django crispy form checkbox
I am using bootstrap, I have a Django crispy form with a checkbox in it, the html looks like this: <div class="form-group"> <div class="checkbox" id="div_id_include"> <label class="" for="id_include"><input class="checkboxinput" id="id_include" name="include" type="checkbox"> Include some data.</label> </div> </div> I am having trouble adapting the following css classes to Django crispy html output format, the checkbox is completely opaque and is not visible. CSS .checkbox-wrapper { position: relative; } td .checkbox-wrapper, th .checkbox-wrapper { margin: 0 0 0 6px; } .checkbox, input[type=checkbox].checkbox, .checkbox-styled { display: block; position: relative; height: 16px; width: 16px; border: 1px solid #d3dbe2; background-color: #ffffff; margin: 0; box-sizing: border-box; vertical-align: middle; } .checkbox, input[type=checkbox].checkbox { z-index: 2; opacity: 0 } .checkbox-styled { border-radius: 3px; z-index: 1 } .checkbox-styled:after { content: ""; display: block; height: 10px; width: 10px; position: absolute; top: 50%; left: 50%; background-color: transparent; background-position: center center; background-size: cover; background-repeat: no-repeat; -webkit-transform: translate(-50%, -50%) scale(0); -ms-transform: translate(-50%, -50%) scale(0); transform: translate(-50%, -50%) scale(0); -webkit-transition: -webkit-transform 0.15s ease-in-out; transition: transform 0.15s ease-in-out; z-index: 2 } .checkbox:active ~ .checkbox-styled, .checkbox:focus ~ .checkbox-styled { border-color: #479ccf } .checkbox:checked ~ .checkbox-styled:after { -webkit-transform: translate(-50%, -50%) scale(1); -ms-transform: translate(-50%, -50%) scale(1); transform: translate(-50%, -50%) scale(1) } .checkbox:indeterminate ~ .checkbox-styled:after { -webkit-transform: translate(-50%, -50%) … -
link django user to perticular site in site framework
I've setup Django sites framework in my project, actually, i want to combine Django user to that particular site What I want to achieve is that when user register from particular site or subsite which register with site framework then that user has to link to that particular site so that we can restrict a user to login to another site with their associate site credential. -
How to use 'heroku run python manage.py migrate' after deploying from the Github?
I wrote an app with Django(1.10.6) and deploy it to heroku through automatic deploys from Github. However, after the deployment, the project on Heroku has some bugs in Database: ProgrammingError at / relation "sport_facility" does not exist LINE 1: ...lity"."open_at", "sport_facility"."close_at" FROM "sport_fac... Thus, I deploy through Heroku Git and it works well. I checked the activity for the previous app, and found there was no migrate when deploying from Github. I wondered how I could be able to run heroku command(like heroku run python manage.py migrate or heroku ps:scale web=2, etc) from command line for the app deployed from Github? -
Django admin "select all" records is not working
Unable to select all from Django Admin dashboard. I'm not using any third party packages besides django-restframework and I haven't overridden the admin template. I've tried multiple browsers and they all have the same issue. I've tried running "./manage.py collectstatic", but that has not resolved the issue. Django version: 1.10.2 This appears to be the same issue: Django admin dashboard, not able to "select all" records But it has not been resolved. Does anyone know what the issue might be? -
How do you filter search results in Wagtail based on a ManyToManyField?
I have a Wagtail site which defines an Event model. These Events have multiple Event Sponsors, which are associated by a ManyToManyField on the EventSponsor model: class Event(index.Indexed, ClusterableModel): title = models.CharField(max_length=255) start_date = models.DateTimeField() end_date = models.DateTimeField(null=True, blank=True) description = RichTextField(blank=True) search_fields = [ index.SearchField('title', partial_match=True, boost=2.0), index.SearchField('description'), index.RelatedFields('sponsors', [ index.SearchField('name', partial_match=True) ]), index.FilterField('end_date'), index.FilterField('sponsors'), ] class EventSponsor(index.Indexed, models.Model): sponsor_id = models.IntegerField() name = models.CharField(max_length=255) url = models.URLField(blank=True) events = models.ManyToManyField(Event, related_name='sponsors') search_fields = [ index.SearchField('name', partial_match=True), ] In addition to this, different Sites on my Wagtail server include Events in their calendar based on a set of selected Event Sponsors specific to that site. So building the calendar listing queryset for each site looks like this: def get_events_for_current_site(request, listing): try: event_sponsor_settings = EventSponsorSettings.objects.get(site=request.site) except EventSponsorSettings.DoesNotExist: # If there's no EventSponsorSettings for this Site, return an empty QuerySet. This shouldn't really ever happen. return Event.objects.none() # Return the selected Events in decending order of start date. query = Event.objects.filter(sponsors__in=event_sponsor_settings.selected_event_sponsors) if listing == 'upcoming_events': return query.order_by('start_date').filter(end_date__gte=timezone.now()) else: return query.order_by('-start_date').filter(end_date__lt=timezone.now()) event_sponsor_settings.selected_event_sponsors is a list of EventSponsor objects. This queryset works just fine for the listing pages. I need the search functionality (using the Elasticsearch backend) on each Site to include only … -
Exclude date via .exclude
I have been looking everywhere for documentation on excluding time and before and after. Ie My app for school is for appointments. They want me to make sure no one can sign up earlier than the current day. If someone could give me a format I have it so i can strip it down to just the day. But not only an solution to the problem but a link to some great detailed documentation as I need date and time for a lot on this project would be good. 'other' : Item.objects.exclude(time |date:"M d, Y"), that is the current code it does not work. I get invalid syntax. If I take out the () of it my page loads so the () is the issue. Any help would be greatly appropriated. -
Run Django app with REST framework
I managed to create a Django application that contains HTML, Javascript and CSS files. When i run the application and i check the network tab after inspecting i see that the files are loaded one by one. What i need is to use my app in different contexts I.E call it from another application so i guess i need to load all the files with one request so i will be able to call my app. I've been told to check REST framework in order to make that happen