Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't get object through publish__month
I write a blog according by the book Django by Example. # blog/models.py from django.contrib.auth.models import User from django.db import models from django.utils import timezone # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique_for_date='publish') author = models.ForeignKey( User, related_name='blog_posts', on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.localtime) class Meta: ordering = ('-publish', ) def __str__(self): return self.title When I get a post in blog/views.py: def post_detail(request, year, month, day, slug): post = get_object_or_404( Post, slug=slug, publish__year=year, publish__month=month, publish__day=day ) return render(request, 'blog/post_detail.html', {'post': post}) It returns 404. If I modify blog/views.py, just filter year, it returns fine: def post_detail(request, year, month, day, slug): post = get_object_or_404( Post, slug=slug, publish__year=year, ) return render(request, 'blog/post_detail.html', {'post': post}) It seems the problem is publish__month. But Django support this method. I can't figure out how to fix it. -
Raven Configuration Git HEAD Error
here is my config: RAVEN_CONFIG = { 'dsn': 'somedsn', 'release': raven.fetch_git_sha(os.path.abspath(os.pardir)), } When I run the server with python manage.py runserver, there is no problem. When I run it with uwsgi I get following error: raven.exceptions.InvalidGitRepository: Cannot identify HEAD for git repository But everything else is just fine. How can I make it to look into right directory in both cases? -
Getting 'DatabaseError' object has no attribute 'message' in DJango
I am trying to run the following code here to save information to the database. I have seen other messages - but - it appears that the solutions are for older versions of Python/DJango (as they do not seem to be working on the versions I am using now: Python 3.6.3 and DJango 1.11.7 if form.is_valid(): try: item = form.save(commit=False) item.tenantid = tenantid item.save() message = 'saving data was successful' except DatabaseError as e: message = 'Database Error: ' + str(e.message) When doing so, I get an error message the error message listed below. How can I fix this so I can get the message found at the DB level printed out? 'DatabaseError' object has no attribute 'message' Request Method: POST Request URL: http://127.0.0.1:8000/storeowner/edit/ Django Version: 1.11.7 Exception Type: AttributeError Exception Value: 'DatabaseError' object has no attribute 'message' Exception Location: C:\WORK\AppPython\ContractorsClubSubModuleDEVELOP\libmstr\storeowner\views.py in edit_basic_info, line 40 Python Executable: C:\WORK\Software\Python64bitv3.6\python.exe Python Version: 3.6.3 Python Path: ['C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP', 'C:\\WORK\\Software\\OracleInstantClient64Bit\\instantclient_12_2', 'C:\\WORK\\Software\\Python64bitv3.6\\python36.zip', 'C:\\WORK\\Software\\Python64bitv3.6\\DLLs', 'C:\\WORK\\Software\\Python64bitv3.6\\lib', 'C:\\WORK\\Software\\Python64bitv3.6', 'C:\\Users\\dgmufasa\\AppData\\Roaming\\Python\\Python36\\site-packages', 'C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP\\libintgr', 'C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP\\libmstr', 'C:\\WORK\\AppPython\\ContractorsClubSubModuleDEVELOP\\libtrans', 'C:\\WORK\\AppPython\\ContractorsClubBackofficeCode\\libintgr', 'C:\\WORK\\AppPython\\ContractorsClubBackofficeCode\\libmstr', 'C:\\WORK\\TRASH\\tempforcustomer\\tempforcustomer\\libtempmstr', 'C:\\WORK\\AppPython\\ContractorsClubBackofficeCode\\libtrans', 'C:\\WORK\\Software\\Python64bitv3.6\\lib\\site-packages', 'C:\\WORK\\Software\\Python64bitv3.6\\lib\\site-packages\\django-1.11.7-py3.6.egg', 'C:\\WORK\\Software\\Python64bitv3.6\\lib\\site-packages\\pytz-2017.3-py3.6.egg'] Server time: Sat, 9 Dec 2017 08:42:49 +0000 -
Django autoescape is not working in render_to_string(template)?
I am drafting an email template to users when they successfully updated their passwords. I used {{ autoescape off }} in the template, which is rendered by using render_to_string(). However, the email content shows the HTML angle brackets directly like this: Hi <span style='color:blue'>user! </span> Your password is updated successfully! I am using Django2.0 and my code looks like this: views.py from django.core.mail import send_mail from django.template.loader import render_to_string def sendmail(request, title) email_title = title email_content = render_to_string('template.html',{'username':request.user.username}) recipient = request.user.email send_mail( email_title, email_content, 'myemail@email.com', [recipient,], ) template.html {{ autoescape off}} Hi <span style='color:blue'>user! </span> Your password is updated successfully! {{ endautoescape }} Is there anything wrong with my code? Otherwise, is autoescape always on while using render_to_string()? -
django: same api url different results with browser and axios/postman
i am using django restframework. i am having an api url. it returns a list of items. The following api url should return the ingredients in the reverse order of name column http://127.0.0.1:8000/api/ingredients/?ordering=-name by Axios/postman: it returns the list but not ordered. with browser url: it returns the list with sorted names. whats happening i am not able to understand -
Ionic 3 sending http post request as application/x-www-form-urlencoded to Django backend
I'm trying to make a post request to my Django backend with Ionic 3 as the front end app. Right now my post method looks like this: register(username, password, email, first_name, last_name) { let url = "https://www.example.com/api/create_user/"; let headers = new Headers(); headers.append("Content-Type", "application/x-www-form-urlencoded"); return this.http.post(url, {"first_name": first_name, "last_name": last_name, "email": email, "username": username, "password": password}, {headers: headers}) .map(res => res.json()); } But Django is receiving it like this: <QueryDict: {'{\n "first_name": "bob",\n "last_name": "bob",\n "email": "bob@bob.bob",\n "username": "bob",\n "password": "bob"\n}': ['']}> And changing the JSON object to a string. I want to properly send form data on my front end so I don't have to do an janky fixes on my Django backend. I tried to add a transformRequest to the header, but this triggers a preflight response because the content-type either gets stripped away or is automatically changed to undefined. How do I change this to properly send the form data so the QueryDict isn't so messed up? -
Create and update data many to many with CreateView and View
I'm very new with Python and Django, currently I'm learning insert many to many in single form, the case I create new Photo with multiple Tags, here the simple version of my code: Models: class Tag(models.Model): tag_title = models.CharField(max_length=50) tag_slug = models.SlugField(max_length=200) class Photo(models.Model): photo_title = models.CharField(max_length=200) taken_at = models.DateTimeField() tags = models.ManyToManyField(Tag) Forms: class AlbumPhotoForm(forms.ModelForm): album_id = forms.NumberInput() tag_list = forms.CharField(max_length=150) class Meta: model = Photo exclude = ('album', 'tags') Template: <div class="form-group"> <label for="photo_title">Photo Title</label> <input class="form-control {% if form.photo_title.errors %} is-invalid {% endif %}" id="photo_title" name="photo_title" placeholder="Put awesome photo title" value="{{ form.photo_title.value|default:'' }}" required> <span class="invalid-feedback">{{ form.photo_title.errors.0 }}</span> </div> <div class="form-group"> <label for="photo_title">Taken At</label> <input class="form-control date-picker {% if form.taken_at.errors %} is-invalid {% endif %}" required id="taken_at" name="taken_at" placeholder="The date photo is taken" value="{{ form.taken_at.value|default:''|date:"m/d/Y" }}"> <span class="invalid-feedback">{{ form.taken_at.errors.0 }}</span> </div> <div class="form-group"> <label for="tags">Tags and Keywords</label> <input class="form-control tags {% if form.tags.errors %} is-invalid {% endif %}" id="tags" name="tag_list" placeholder="Tag separated by comma" value="{{ form.tags.value|default:'' }}"> <span class="invalid-feedback">{{ form.tags.errors.0 }}</span> </div> The problem I can figure what best way to insert new tag and fetch if it exists before in CreateView or Update view, input tag_list contain tag title separated by comma (like: vitage,awesome,family,etc). Here what … -
elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]')
I am using haystack with elasticsearch backend for full text searching. I am wanting to show the search result using ajax. However I am getting an error of elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]') . Here is my code url(r'^search', views.search_furniture, name="search-furnitures"), def search_furniture(request): furnitures = SearchQuerySet().autocomplete(content_auto=request.POST.get('search_text', '')) context = {'furnitures': furnitures} return render(request, 'search/ajax_search.html', context) class FurnitureIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True, template_name="search/indexes/furniture/furniture_text.txt") name = indexes.CharField(model_attr='name') category = indexes.CharField() content_auto = indexes.EdgeNgramField(model_attr='name') def get_model(self): return Furniture def index_queryset(self, using=None): return self.get_model().objects.all() ajax_search.html {% if furnitures.count > 0 %} {% for furniture in furnitures %} <li>{{ furniture.object.name }}</li> {% endfor %} {% else %} <li>None to show</li> {% endif %} base.html {% block navbar %} {% include "includes/navbar.html" %} {% endblock navbar %} {% block js %} {% include "includes/js.html" %} <script> $('.search').keyup(function() { $.ajax({ type: "POST", url: "/search/", data: { 'search_text' : $('.search').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: 'html' }); }); function searchSuccess(data, textStatus, jqXHR) { $('#search-results').html(data); } </script> {% endblock js %} navbar.html {% include 'search/search.html' %} search.html <form method="post" action="/search" class="navbar-form search" role="search"> {% csrf_token %} {{ form.non_field_errors }} <div class="form-group"> {{ form.as_p }} </div> <div class="input-group"> <input type="text" name="q" class="form-control search" placeholder="Search"> … -
the migrate in django give me this error
i want to run a django app i use python3.6 manage.py makemigrations something the something is name of apps that i write here then i write python3.6 manage.py migrate Operations to perform: Apply all migrations: searchapp, account, payment, sessions, contenttypes, baang, redirects, sites, support, myprofile, posts, management, sidebars, myresources, auth, admin Running migrations: Rendering model states... DONE Applying account.0001_initial... OK Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying baang.0001_initial... OK Applying myprofile.0001_initial... OK Applying payment.0001_initial... OK Applying management.0001_initial... OK Applying management.0002_auto_20171209_1006... OK Applying myresources.0001_initial... OK Applying posts.0001_initial... OK Applying sites.0001_initial... OK Applying redirects.0001_initial... OK Applying searchapp.0001_initial... OK Applying sessions.0001_initial... OK Applying sidebars.0001_initial... OK Applying sites.0002_alter_domain_unique... OK Applying support.0001_initial... OK` and then it gives me this error Traceback (most recent call last): File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 112, in execute return self.cursor.execute(query, args) File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/MySQLdb/cursors.py", line 226, in execute self.errorhandler(self, exc, value) File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorvalue File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/MySQLdb/cursors.py", line 217, in execute res = self._query(query) File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/MySQLdb/cursors.py", line 378, in _query rowcount = self._do_query(q) … -
how do i check my email is available in database or not
i wrote one model that is having email field i added some emails in it by admin what i need is when i typed any email that should check with my database email if exist it should show email is already there models.py #in my database already some data is there class Friend(models.Model): email = models.EmailField(max_length=100) def __str__(self): forms.py class FriendForm(forms.ModelForm): class Meta: model = Friend fields = ['email'] views.py def check(request): form = FriendForm(request.POST or None) if form.is_valid(): form = Friend.objects.filter(**form.cleaned_data) context = { 'form': form } return render(request, "one.html", context) i imported every thing when i am trying this code it is directly rendering to one.html i need is it should check if email is there in database then only it should render i am new to django so please help me -
User Authentication for aws using Python
I'm working on a project with Python(3.6) & Django(1.10) in which I'm using aws apis but I'm new to aws and don't know how to authenticate a user. My scenario is: I need to access user's aws resources like projects list, buckets list etc, for that, I need to authenticate the user when making a request to a particular API. How can I do that in python? I'm new to aws.So, please don't mind my question. Help me, please! Thanks in advance! -
Upload_Path_Handler file path for Django ImageField not fetchable from HTML file
I've attempted to use Upload_Path_Handler in order to allow for dynamic folder names (such as the upload date, item ID, etc.) in saving image files uploaded by users, so as to prevent duplicate instances. The problem is that the directory which I've returned is too 'deep' to be retrieved through the HTML file, in that, it begins with the name of the app (in this case, 'vault'). The broken path served for the image in the HTML file is as follows: <img src="vault/static/vault/images/recordimages/r_1/2017-12-09_03-27-42/300x300.jpg"> However, by using inspector element to exclude the app name 'vault' at the beginning, I am able to successfully retrieve the image: <img src="/static/vault/images/recordimages/r_1/2017-12-09_03-27-42/300x300.jpg"> The broken path is served in the raw html file as: <img src="{{ record.w_image }}"> And the model referenced, w_image, is as follows in models.py: w_image = models.ImageField(null=False, blank=True, verbose_name='Record Image:', upload_to=upload_path_handler) Then, of course, is upload_path_handler: def upload_path_handler(self, filename): return "vault/static/vault/images/recordimages/r_{id}/{date}/{file}".format(id=self.id, file=filename, date=datetime.datetime.utcnow().strftime('%Y-%m-%d_%H-%M-%S')) If I were to begin the return path at /static/, it would then instead save the images in WebsiteName/static/../.. as opposed to WebsiteName/vault/static/../.. (Remember, the aim here is to keep the /static/ directory a subdirectory of our app, 'vault') How can I allow for the image to be retrievable … -
Websockets on production chat apps:
As I am beginning to work my way through web-sockets using Python (Django Channels in this case), I am beginning to wonder how companies scale chat applications. Take this specific problem: User A has a list of "group messages" that they are involved in. User A is capable of receiving notifications from each of the groups. Lets suppose User A has 5 different groups he would like real time notifications for. Does User A have 5 separate web socket connections? This is easiest, but the bulkiest and surely wont scale (what if we had 20 chats per user). It is quite easy to make a Django Channels "Group" that listens and sends notifications to one specific group of people. Does User A instead have 1 web socket connection taking all notifications from many different locations? If so, what is User A subscribing to on the backend? In Django Channels, a websocket is made when users subscribe to a "Group". If we wanted one user per "Group', this would seem counter intuitive. In this case, User A is subscribing to their own personal "Group" and other backend services are delivering messages to that specific "Group" based on other logic that is … -
Export a File (CSV, PDF) From Django Admin from Form Inputs
All within the Django admin, I'd like to enter form fields related to generating a report. Fields you'd expect in a report: report name, report type, start and end dates, report fields, etc. How would one take these inputs, grab the inputs from the request, pass these inputs to an API (in the background), then process it (in queue-like fashion), finally create a CSV or PDF to download? I'm fine with creating the admin model form and I think grabbing the inputs when the form is submitted in the admin, then I think I simply pass those inputs to my other API code to process... My questions are: When the third-party API is processing the request, is there a special way to handle this lag time? Where and how would I return the result - which is a CSV or PDF - in the admin interface? The /change/ page? Is there best-practice for this? I haven't been able to find an example of this when dealing with the admin. I'm not new to Python but am somewhat new to Django. -
Why is my django urlpattern not resolving?
So I'm creating a small ecommerce website for a friend and cannot work out why the url won't resolve itself. For the sake of simplicity whilst making the website I'm using a product called "number 1". It has a slug field of "number-1" and on the product page clicking on the product takes a user to "/shop/number-1" My url pattern for this is: url(r'^<slug:url>', views.item, name='products') with the view: def item(request, url=""): products = product.objects.get(url=url) return render(request, 'shop\product.html', {'products', products}) As far as I can tell this should render my product.html template but instead it returns a 404 and I'm not sure why? If it helps I have other views, such as product types set within the same views and they work fine so as far as I can tell its that the slug:url isn't being used in the views.item, or the view isn't getting the context properly. Also I'm on django 1.11.7 for this project. Thanks in advance. -
Model Form drop-down (select) field not displaying correct rows to choose from
I have a Parent Model that uses a Foreign Key that points to a Child Model. In this case, the "Child Model" is called Mstrgensalutationtype (which is really Salutations). The Parent Model is being used to create a Model Form Basically, below is what I get when trying to choose a Salutation Type. What I need to see is Mr. Ms. Mrs. Prof. Dr. Question: What am I doing wrong here? TIA models.py - used as a Child Model class Mstrgensalutationtype(models.Model): saltypeid = models.BigIntegerField(primary_key=True) lang = models.CharField(max_length=2, blank=True, null=True) shortval = models.CharField(max_length=7, blank=True, null=True) salutationlong = models.CharField(max_length=20, blank=True, null=True) class Meta: managed = False db_table = 'MstrGenSalutationType' def __unicode__(self): return u'%s ' % ( self.shortval ) models.py - used as a Parent Model class Mstrstorehead(models.Model): tenantid = models.BigIntegerField(primary_key=True) extrefacctno = models.CharField(max_length=20, blank=True, null=True, verbose_name="Account Reference No") [... snip ...] contactsalutationid = models.ForeignKey(Mstrgensalutationtype, models.DO_NOTHING, db_column='contactsalutationid', blank=True, null=True, verbose_name="Salutation") [... snip ...] class Meta: managed = False db_table = 'MstrStoreHead' -
disabled field is marked as required after passing null=True
I have a form where there is a field like quantity, rate, basic_amount(disabled), vat, other_expenses and net_amount(disabled). The basic_amount field is the calculation from quantity and rate and net_amount is the calculation of basic_amount, other_expenses and vat. For this I used signal for saving to the database when user submits the form. When i submit the form, I get an error saying basic_amount and net_amount is required, though I have passed blank=True, null=True attribute to them. How can i now save basic_amount and net_amount? Here is my code class PurchaseOrder(models.Model): item = models.ForeignKey(Item, blank=True, null=True) quantity = models.PositiveIntegerField(default=0) rate = models.DecimalField(default=0.0, max_digits=100, decimal_places=2) basic_amount = models.DecimalField(default=0.0, max_digits=100, decimal_places=2, blank=True, null=True) vat = models.CharField(max_length=10, blank=True, null=True) other_expenses = models.DecimalField(default=0.0, max_digits=100, decimal_places=2) net_amount = models.DecimalField(default=0.0, max_digits=100, decimal_places=2, blank=True, null=True) def save_basic_amount_and_net_amount(sender, instance, *args, **kwargs): if (instance.quantity and instance.rate): instance.basic_amount = instance.quantity * instance.rate if (instance.basic_amount and instance.vat and instance.other_expenses): instance.net_amount = instance.amount - instance.other_expenses - instance.vat pre_save.connect(save_basic_amount_and_net_amount, sender=PurchaseOrder) class PurchaseOrderForm(forms.ModelForm): basic_amount = forms.DecimalField(disabled=True) net_amount = forms.DecimalField(disabled=True) class Meta: model = PurchaseOrder exclude = ('office', 'timestamp', 'updated', ) def purchase_order(request): form = PurchaseOrderForm(request.POST or None) if request.method == "POST" and form.is_valid(): office_instance = OfficeSetup.objects.get(owner=request.user) new_form = form.save(commit=False) new_form.office = office_instance new_form.save() messages.success(request, 'Thank … -
How can I upgrate plan on Heroku from Hobby-dev to Hobby Basic?
I would like to upgrate plan on Heroku with my Django app from Hobby-dev to Hobby Basic? At the moment heroku pg:info returns: Plan: Hobby-dev Status: Available Connections: 0/20 PG Version: 9.6.4 Created: 2017-11-12 19:20 UTC Data Size: 135.9 MB Tables: 19 Rows: 1272760/10000 (Above limits, access disruption imminent) Fork/Follow: Unsupported Rollback: Unsupported Continuous Protection: Off Add-on: postgresql-cub... I tried to use this but I am not sure which way should I choose? -
Package backend.apps missing Django
I've been trying to setup a Django site, but when I run python3 manage.py make migrations I get the error ModuleNotFoundError: No module named 'backend.apps' I have installed Django and package backend. -
Including the current date in TimedRotatingFileHandler
Is it possible to somehow overwrite the functionality of Django's TimedRotatingFileHandler method to include the date in the current iteration of the file? By which I mean, have the current filename be dated as mylog.log.YYYY-MM-DD as opposed to just mylog.log with the date being added in when it gets rotated out? Here is my basic code I am using: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'session': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': '/efs/mylog.log', 'when': 'midnight', # this specifies the interval 'interval': 1, 'backupCount': 1, }, .... -
Integrating Angular 2 frontend with python app
I'm supposed to make an Angular client app, and integrate it with a python server, and not sure if I should also consider using any python framework (such as Django or Flask) alongside my frontend framework. I've got some minimal experience with making Django apps, but not sure what would be the profit of using it just for the frontend and not as a fullstack framework. Using angular on the front means rendering the data on the front (in contrast to classic django design), so is there any good reason to use django on my backend over just a plain python environment? Is it easier to make an API using django for example? Another basic question that might sound a little stupid but stems from the fact that i'm new to web development, is where is the server-side code of a regular angular app is sitting? or in other words, what is "ng serve" command doing in the background? (as i guessed it runs a server). But this question is just for general understanding. And lastly, in either way, should the architecture for this kind of app be creating an standalone angular app for the front, whilst making another standalone … -
Change the appearance of labels and input fields (from a Model Form) used in a DJango template
I am using a script below (that resides in a DJango template) to display input fields that are associated with a particular Model Form. The purpose of this template is to add and modify data for a Model. The name of the template is : model_name_form.html (ex: customer_form.html for the Model representation of the table Customer) In order to add/modify data, the Model Form is being used. The problem is that when using the script below, a type of default presentation is being used for the fields. In my case, the fields need to be more customized. The customized labels and input fields make the form look much nicer. I start out with this (which is in the template that displays the form): {% for field in form %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small"> {{ field.errors }} </span> </div> <label class="control-label col-sm-2"> {{ field.label_tag }} </label> <div class="col-sm-10"> {{ field }} </div> </div> {% endfor %} Which turns into this: <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small"> </span> </div> <label class="control-label col-sm-2"> <label for="id_companyname">Company Name:</label> </label> <div class="col-sm-10"> <input name="companyname" id="id_companyname" type="text" maxlength="30"> </div> </div> But what is needed is a label/input presentation similar to the … -
Django Queryset for concat query fullname of first_name and last_name
I would like to do a fullname (first_name concat last_name) search/query in Django. The following is my model: class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee') company = models.ForeignKey(Company) username = models.CharField(max_length=30, blank=False) first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) created_at = models.DateTimeField(auto_now_add=True) For example we have an entry like this. first_name:"Michael", last_name:"Jackson" I want to be able to query full name "michael jackson". If can show without case sensitive would be great as well. This other stackoverflow question is similar but the answers is not fulfilling this particular requirement Querying full name in Django. We want to be able to do a concat search. -
psycopg2.ProgrammingError: column of relation does not exist
Trying to insert data into PostgresSQL database. Python code: myFields = ((DOT_Number,),(Entity_Type,),(Operating_Status,),(Legal_Name,), (Phone,),(Address,) ) query = """ INSERT INTO saferdb_question( DOT_Number, Entity_Type, Operating_Status, Legal_Name, Phone, Address)VALUES ( %s, %s, %s, %s, %s, %s);""" cur.execute( query, myFields) Getting error: Traceback (most recent call last): File "scraper.py", line 189, in <module> cur.execute( query, myFields) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/psycopg2/extras.py", line 144, in execute return super(DictCursor, self).execute(query, vars) psycopg2.ProgrammingError: column "dot_number" of relation "saferdb_question" does not exist LINE 1: INSERT INTO saferdb_question( DOT_Number, Entity_Type, Oper... SQL from PostgreSQL that created the table: CREATE TABLE public.saferdb_question ( id integer NOT NULL DEFAULT nextval('saferdb_question_id_seq'::regclass), "DOT_Number" character varying(10) COLLATE pg_catalog."default" NOT NULL, ... "Phone" character varying(15) COLLATE pg_catalog."default" NOT NULL, "Address" character varying(200) COLLATE pg_catalog."default" NOT NULL, ) WITH ( OIDS = FALSE ) TABLESPACE pg_default; ALTER TABLE public.saferdb_question OWNER to postgres; -
How tooutput what is being run for Django migrations
In Django 1.9.6 with MySQL 5.7, Django migrate task is taking so long and I'd like to review why so. Here are my commands python manage.py makemigrations python manage.py migrate And it seems to be stuck at: Operations to perform: Apply all migrations: webapi, customers, jobs, finance, installations, common, bills, corporate. Running migrations: <------- stuck here for 10 minutes I'd like to view what is going on and which migration is being run. Is there a way to enable it?