Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Subquery returns more than 1 row in Django while connecting models
I want to get authorName whenever someone search for a book and yeah I have tried many to many but it is very confusing and after researching some things I got to a view which I thought should work fine but it is returning an error "1242, 'Subquery returns more than 1 row'" here are some of the relevant code: Models from __future__ import unicode_literals from django.db import models class Books(models.Model): bid = models.BigIntegerField(primary_key=True) bname = models.CharField(max_length=200, blank=True, null=True) bdescription = models.TextField(blank=True, null=True) def __str__(self): return self.bname class Authors(models.Model): aid = models.AutoField(primary_key=True) aname = models.CharField(max_length=200, blank=True, null=True) adescription = models.TextField( blank=True, null=True) def __str__(self): return self.aname+"\n" class Bookauth(models.Model): bid = models.ForeignKey(Books, on_delete=models.DO_NOTHING, db_column='bid', blank=True, null=True) aid = models.ForeignKey(Authors, on_delete=models.DO_NOTHING, db_column='aid', blank=True, null=True) Views for what I thought was right def authbook(request): s = Authors.objects.all() r = Books.objects.filter(bookauth__aid = s).values() return HttpResponse(r) Guide me please Django gods!! -
How to pass a Model to a Generic Serializer from a ViewSet in Django Rest Framework
I'm trying to create a Generic TemporalModelSerializer. The TemporalModelSerializer creates a new record and terminates the old record. It is successful in doing so, however now i would like to use the Serializer for other models. Is it possible to pass the model into the Serializer and then use it in this line? Thanks OptionMaster.objects.filter(pk=instance.pk, vflag=1).update(**new_record) Views class OptionMasterViewSet(viewsets.ModelViewSet): serializer_class = TemporalModelSerializer queryset = OptionMaster.objects.filter(vflag=1) lookup_field = 'contractcode' The Generic TemporalModelSerializer class TemporalModelSerializer(serializers.ModelSerializer): vf = serializers.HiddenField(default=datetime.now()) vt = serializers.HiddenField(default=datetime(3000, 12, 31, 23, 00, 00, 000000)) vflag = serializers.HiddenField(default=1) vu = serializers.HiddenField(default='Theodore') class Meta: model = OptionMaster exclude = ('vt', 'vf', 'vu', 'vflag') def update(self, instance, validated_data): time_now = datetime.now() old_record = {} new_record = {} for field in instance._meta.get_fields(): old_record[field.name] = getattr(instance, field.name) new_record[field.name] = validated_data[field.name] old_record['vt'] = time_now old_record['vflag'] = 0 new_record['vf'] = time_now self.delete_me(old_record) OptionMaster.objects.filter( pk=instance.pk, vflag=1).update(**new_record) return instance def delete_me(self, old_record): obj = OptionMaster.objects.create(**old_record) -
Django Rest Framework foreign key multiple data
I have a model call Schedule, it is like reminder function. I also have another model called Family which user can add family member in it. So in schedule, i create a foreign key to link family inside so that it will include the family member id in it. Here is the how my API for schedule looks like: https://imgur.com/a/bwYDn And here are my questions. As you can see based on the image in above link, the userId is a drop down. is it possible to make it userId = self.request.user.userId ? In the schedule api, the familyId is a drop down that consist of all family member(basically, even other people who added their family), is there a way to filter it so that it will only shows a dropdown of only the current user familyId appear ? When creating a schedule, user can only insert 1 familyId. Is there a way to choose more than 1 familyId ? For eg, user can insert familyId 1 and 2 Here is my code models.py class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=40, blank=True, null=True) birthday = models.DateField(blank=True, null=True) birthTime = models.TimeField(blank=True, null=True) class Family(models.Model): userId = … -
Future-proofing my application code for readability (Django, Beginner)
The aim of my website is to have a page, let's call it "Random Question!" Each time the user enters the page, a set of numbers are randomly generated, and they have to correctly answer the question: numbera + number b . IF they are correct, they go to a page that says "Correct" and then they are redirected back to the same page, again, with a different set of numbers. Now, the issue is, on the first page "Random Question!", I want to add another question to it. Views.py: def form_handle(request): if request.method == 'POST': form = MyForm(request.POST) # if post method then form will be validated if form.is_valid(): cd = form.cleaned_data num1 = cd.get('num1') a = request.session.get('a', 0) b = request.session.get('b', 0) if float(num1) == float(a + b): # give HttpResponse only or render page you need to load on success return render(request, 'sectipn1part1success', {}) else: # if sum not equal... then redirect to custom url/page return HttpResponseRedirect('rr/') # mention redirect url in argument else: a = random.randrange(5,10); b = random.randrange(10,20); request.session['a'] = a request.session['b'] = b question1 = ('What is ' + str(a) + ' + ' + str(b) + ' ?') form = MyForm() # blank … -
Saving Django Inline Formsets
I've been working on a report form and I've ran into a bit of a road block. The report is basic, with exception to the fact that the report can have many punches (clock in, clock out). To make that usable on the form I have to generate a custom form with attributes. When I do that, I am unable to save the inline form data. Where am I going wrong here? ''' views.py ''' def reportupdateview(request, pk): form = ServiceReportUpdateForm report = get_object_or_404(ServiceReportModel, pk=pk) formset = PunchesFormSet(instance=report) print(report) if request.method == 'POST': reportform = form(request.POST, instance=report) punchesform = form(request.POST, instance=report) if reportform.is_valid(): if punchesform.is_valid(): reportform.save() punchesform.save() return redirect('service:report-update', pk=report.pk) if request.method == 'GET': report.updated_by = request.user reportform = form(instance=report) context = { 'report': reportform, 'punches': formset } return render(request, 'service/report-update.html', context) ''' forms.py ''' class ServiceReportUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ServiceReportUpdateForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: self.fields['request_number'].required = False self.fields['reported_by'].widget.attrs['readonly'] = True self.fields['updated_by'].widget.attrs['readonly'] = True self.fields['equipment'].widget.attrs['readonly'] = True self.fields['report_reason'].widget.attrs['readonly'] = True def clean_reported_by(self): instance = getattr(self, 'instance', None) if instance and instance.pk: return instance.reported_by else: return self.cleaned_data['reported_by'] class Meta: model = ServiceReportModel fields = [ 'site', 'invoiced', 'paid', 'request_number', 'reported_by', 'updated_by', 'equipment', 'report_reason', … -
Intellij complains of incorrect configuration for django project
Whenever I run my python django application in Intellij, it shows me a dialog box saying configuration is incorrect and gives me an option to edit or run anyway. Following is the screenshot of my configuration. Not sure what is it that I am missing. Update: It does show intermittently in the same configuration dialog box that Django project root is not configured and I am not sure how I can do that. Also, when I run the project anyway, it says, No manage.py file specified in Settings->Django Support -
Speed for querying the whole database using objects.filter()
I am using django to make a website in which a user can log in and upload files. I was wondering whether using files = upload.objects.filter(user=User) to filter all the files uploaded by a specific user an efficient way. What if my database has thousands of files in it. Will this method work in an efficient way? Here's models.py: class upload(models.Model): files = models.FileField() title = models.CharField(max_length = 30) user = models.ForeignKey(User,on_delete=models.CASCADE) -
How can i encryption database username and password which in the django settings file?
Database setting like this, any encryption methods: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '*&^%$#', 'USER': '*&^%$#@', 'PASSWORD': '*&^%$#', 'HOST': '*&^%$#', 'PORT': '3306', # 'OPTIONS': {'threaded': True} this is used in production env and suit for oracle db } } -
Django - Do different queries depending on value of field
I'm stuck on a seemingly simple issue. I want to do a different queryset if sold_data is empty. Is there an effective way to do this? Or do I need to use a for loop and loop over all the listing objects and check each one? class Listing(models.Model): list_price = models.IntegerField() sold_price = models.IntegerField(null=True, blank=True) ... other fields data = Listing.objects.filter(...) # Note: I had already made other queries if sold_price == None: data = data.filter(list_price__gte=1) else: data = data.filter(sold_price__gte=1) -
Annotate QuerySet with first value of ordered related model
I have a QuerySet of some objects. For each one, I wish to annotate with the minimum value of a related model (joined on a few conditions, ordered by date). I can express my desired results neatly in SQL, but am curious how to translate to Django's ORM. Background Let's say that I have two related models: Book, and BlogPost, each with a foreign key to an Author: class Book(models.Model): title = models.CharField(max_length=255) genre = models.CharField(max_length=63) author = models.ForeignKey(Author) date_published = models.DateField() class BlogPost(models.Model): author = models.ForeignKey(Author) date_published = models.DateField() I'm trying to find the first mystery book that a given author published after each blog post that they write. In SQL, this can be achieved nicely with windowing. Working solution in PostgreSQL WITH ordered AS ( SELECT blog_post.id, book.title, ROW_NUMBER() OVER ( PARTITION BY blog_post.id ORDER BY book.date_published ) AS rn FROM blog_post LEFT JOIN book ON book.author_id = blog_post.author_id AND book.genre = 'mystery' AND book.date_published >= blog_post.date_published ) SELECT id, title FROM ordered WHERE rn = 1; Translating to Django's ORM While the above SQL suits my needs well (and I could use raw SQL if needed), I'm curious as to how one would do this in QuerySet. … -
how to add the annotate query in fetching the data in django
the problem is that i want to count total number of address in same area on my searching views.py if query: family = family.filter( Q(head__name__icontains=query) | Q(address__icontains=query) | Q(head__birth_date__icontains=query) | Q(head__gender__icontains=query) | Q(spouse__name__icontains=query) | Q(tribe_type__icontains=query) | Q(head__religion__icontains=query) | Q(head__highest_educational_attainment__icontains=query) ).annotate( total_address=Sum( Case( When(address__icontains=query, then=Value(1)), default=Value(0) ) ) ) # distinct() page = self.paginate_queryset(family) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(family, many=True) return Response(serializer.data) and i want to return as well the total_address in my return page i am using restful api to fetch the data`s any help is highly appreciated -
Unable to login to the admin panel in Django
The site is working fine but when I switch to http://127.0.0.1:8000/admin/ it shows AttributeError at /admin/ .I tried to include MIDDLEWARE_CLASSES in the mysite/settings.py but to no avail . Here are some details : Django mysite.settings INSTALLED_APPS = [ 'personal', 'blog', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] http://127.0.0.1:8000/admin/ page :: Django mysite.urls :: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('personal.urls')), url(r'^blog/', include('blog.urls')), ] Am I missing something? Ask for more info if required . Thanks! -
django utf-8 metatag not extending to inheriting templates
I have template inheritance set up with utf-8 metatag: layout.html would work fine with ä in it. <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>{{ title }}</title> {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'app/css/theme-default.css' %}" /> </head> <body> ääää {% block content %}{% endblock %} </body> I can use unicode charset in the layout.html with no problems. ä ü õ etc. But not in the inheriting templates. events.html like this would give a error: {% extends "app/layout.html" %} {% block content %} ä {% endblock %} UnicodeDecodeError at /events.html 'utf-8' codec can't decode byte 0xe4 in position 54: invalid continuation byte -
django removes image on update save
I have the following clean method by which I reduce an image if it is too large: class CompanyForm(forms.ModelForm): class Meta: model = Company exclude = ('limited') def clean_image(self): image_field = self.cleaned_data.get('image') if image_field: reduced_image = reduce_image(image_field, 550) return reduced_image else: raise forms.ValidationError('You must upload a square logo image') return image_field My reduce image looks like the following: def reduce_image(image_field, height_max): if image_field: try: image_file2 = BytesIO(image_field.read()) image = Image.open(image_file2).convert('RGB') print(image) except: #raise ValidationError('There was a problem with the image, please try another.') print('returning from image errror') return image_field w, h = image.size print('image width:'+str(w)) print('image height:'+str(h)) if h > height_max: print('height toolarge') ratio = h/float(w) new_height = ratio * height_max image = image.resize((int(height_max), int(new_height)), Image.ANTIALIAS) image_file = BytesIO() image.save(image_file, 'JPEG', quality=90) image_field.file = image_file print(image_file) return image_field The first time I save, it saves no problem. When I save a second time to update the model, it removes the image. Why might this be happening? -
Django aggregate avg price by product category
I have this view: def MainStatsView(request): leads = Leads.objects.all() university = University.objects.all() price = Leads.objects.aggregate(Avg('price')) context = { 'leads':leads, 'university':university, 'price':price, } return render(request,'stats/stats_main.html',context) I am trying to get the average price of properties (the product) that generated leads at each university (the category). I am having trouble finding the avg price based on university. I tried using a for loop but that doesn't seem to do the trick. Also here is my loop: {% for uni in university %} <tr> <td>{{ uni.u_name }}</td> <td>{{ price }}</td> <td>{{ lead.school }}</td> <td>{{ lead.featured }}</td> <td>{{ lead.price }}</td> </tr> {% endfor %} I'm a little all over the place here so that is why it looks overly messy. Here is an image of the result. It's giving me the avg on the price of all properties that have generated leads rather than for one school specifically (which is what I want). -
Static folder is not working on Django
I'm beginning at Django and I don't know why but it seems like Django can't find my static folder. Here's how I did it : # IN MY SETTINGS FILE STATIC_URL = '/static/' # IN MY APP "accounts", IN base.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'accounts/basic.css' %}"> # (MAIN FOLDER) -> (accounts (APP)) -> (static) -> (accounts) -> basic.css I tried to put some red color on my h2 but it's not working, and I see no mistakes. Sorry if this is a dupe but it seems like it has no mistakes for me and I'm lost.. Thanks ! -
python, django code doesn't work in html
This is my html file code part product.html <aside> <div id="news"> <h2 class="heading">News</h2> <div style="clear: both"><br></div> {% for articles in news_articles %} <div id="articles"> <div class="article"> <a href="{{ articles.article.get_absolute_url }}"> <img src="{{ articles.image }}"> <div style="clear: both"></div> <span></span><div style="clear: both"></div> </a> <em>{{ articles.article.created }}</em> <div style="clear: both"><br></div> </div> {% endfor %} </div> <a href="" title="View More Articles"> <div id="btn"> <span>View More</span> </div> </a> </div> </aside> This is my views.py file code part views.py def product(request, product_id): product_images = ProductImage.objects.filter(is_active=True, is_main=False, product=product_id) product = Product.objects.get(id=product_id) links = ProductDownload.objects.filter(is_active=True, product=product_id) return render(request, 'products/product.html', locals()) def new(request, product_id): news_articles = NewsImage.objects.filter(is_active=True, is_main=True) article = Article.objects.get(id=product_id) return render(request, 'news/article.html', locals()) This is my models.py file code part models.py class Product(models.Model): name = models.CharField(max_length=128, blank=True, null=True, default=None) description = models.TextField(default=None) processor = models.CharField(max_length=300, blank=True, null=True, default=None) video = models.CharField(max_length=300, blank=True, null=True, default=None) ram = models.CharField(max_length=300, blank=True, null=True, default=None) disk_space = models.CharField(max_length=300, blank=True, null=True, default=None) oS = models.CharField(max_length=300, blank=True, null=True, default=None) video_trailer = models.CharField(max_length=10000, blank=True, null=True, default=None) img = models.CharField(max_length=10000, blank=True, null=True, default=None) category = models.ManyToManyField(ProductCategory, blank=True, default=None) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) slug = models.SlugField(primary_key=True, max_length=250, unique=True, default=None) def __str__(self): return '%s' % self.name def get_absolute_url(self): return reverse('product', args=[str(self.slug)]) class ProductImage(models.Model): product = models.ForeignKey(Product, … -
Getting a url to read the HTML output from a .fcgi file and not the contents of the .fcgi file (shared server using fastcgi)
My question is how do I get a browser to read the HTML output from a .fcgi file and not the contents of the .fcgi file. I am using a shared server, linux, Django 2.0, Python 3.6.4, flup6. Because fastcgi is deprecated post Django 1.8 and Bluehost doesn't use WSGI and only FastCGI (mod_fastcgi) I am using what NetAngels made available: https://github.com/NetAngels/django-fastcgi My .htaccess file is the project folder with my .fcgi file as is commonly recommended. My .htaccess reads: AddHandler fastcgi-script.fcgi RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)% app.fcgi/$1 [QSA, L] My .fcgi file reads: #!/homeX/user/python3.6/bin/python36 import sys, os project_name = "app" sys.path.insert(0, "homeX/user/python3.6/bin/python36") sys.path.append("directory/of/my/project/app") sys.path.append("directory/of/my/project/app/app") sys.path.append("directory/of/my/project/app/app/app") sys.path.append("directory/of/site-packages") sys.path.append("directory/of/site-packages/flup") sys.path.append("directory/of/site-packages/django") os.chdir("directory/of/my/project/app/app/app") os.environ['DJANGO_SETTINGS_MODULE'] = "settings" from django_fastcgi.servers.fastcgi import runfastcgi from django.core.servers.basehttp import get_internal_wsgi_application wsgi_application = get_internal_wsgi_application() runfastcgi(wsgi_application, method="prefork", daemonize="false", minspare=1, maxspare=1), maxchildren=1) I have made sure to: chmod 0755 app.fcgi I am able to type into the linux SSH: app.fcgi This is what comes up in the SSH terminal: WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI! WSGIServer: missing FastCGI param SERVER_NAME required by WSGI! WSGIServer: missing FastCGI param SERVER_PORT required by WSGI! WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI! Not Found: / Status: 404 Not Found Content-Type: text/html … -
django-taggit - display existing tags on the django-admin add record page
I have created a test vlog application using django/python and django-taggit. The vlog and tags are working as they should. However, I want to list all the existing tags in the django-admin interface for new and updated vlog entries - similar to displaying the tags as a filter on the django-admin list page. This will make the selection of new or existing tags for each new or updating vlog entry that much easier. Here is what I mean by adding the tags as help-text on the tags input field: My models.py code: class VlogDetails(models.Model): .... vlog_video_image_url = models.URLField(null=False, blank=False, max_length=250, unique=True, help_text='http://img.youtube.com/vi/You_Tube_URL/0.jpg') .... tags = TaggableManager(help_text='List all the available tags here.') Here is the django-admin input form interface: Is it possible to display the existing tags in another manner on the new / edit django-admin page? I have already listed the existing / existing tags on the django-admin list page as a filter as shown below. This filter display does not display on the new / update input forms. django-admin filter code: class VlogDetailsAdmin(BaseDetailsAdmin): .... list_filter = [ 'vlog_date_published', 'tags', 'vlog_timestamp_added', 'vlog_timestamp_updated' ] I have tried several things but none work and I cannot find any related ideas in the … -
Detecting if my page is being loaded in an iFrame in a Django view
How can I detect in a view function that the page is being loaded in an iFrame? I want to change the page slightly if that is the case. Is there any way to do this? Note, Im not looking for click jacking protection. I want to make changes to my view if the page is being loaded in an iframe. -
Django ORM - How to perform complex GROUP BY with values().annotate().values()
I'm trying to convert as much raw SQL to use the Django ORM as I can, and I've run into a snag. I'm trying to perform a query similar to this one: SELECT table.x, MAX(table.y) AS y, table.group_category, table.group_number, FROM table GROUP BY table.group_category, table.group_number So far, what I've been trying has been some permutation of this: q = MyModel.objects\ .filter(**filter_kwargs)\ .values('group_category', 'group_number')\ .annotate(y=Max('y'))\ .values('x','y','group_category','group_number') However, this doesn't seem to work. If I exclude the last values(), it produces the following (roughly): SELECT MAX(table.y) AS y, table.group_category, table.group_number, FROM table GROUP BY table.group_category, table.group_number It doesn't select table.x. But if I include the last values()... SELECT table.x, MAX(table.y) AS y, table.group_category, table.group_number, FROM table GROUP BY x, y, table.group_category, table.group_number It groups by x, y. So what clearly seems to be happening is that the all of the values are replaced and annotate uses whatever values the QuerySet is given (because it's evaluated lazily?). The docs on aggregation and values seem to suggest that doing the two values functions in this order would have the desired effect, and I found a writeup (from 2013) that also suggests this. Am I doing something wrong? Is this still possible in the Django … -
Django conn= connet(dsn, connetion_factory, async=async) django.db.utils.OperationalError psycopg2
I am working on the connection of postgresql 9.5 and Django 1.11 in wimdows 7, but it throws me an error install python 3.4.2, add path install postgresql 9.5.10, add path install virtualenv version 15.1.0 create virtualenv myenv run Scripts\myenv\activate install psycopg2-2.6.2.win32-py3.4-pg9.5.3-release.exe, add folder psycopg2 in C:\proyectos\myenv\Lib\site-packages install Django 1.11 create project Django => django-admin.py startproject redsocial in the folder redsocial => django-admin.py startapp goodpeople in Sublime text3 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'goodpeople', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'goodpeople', 'USER': 'postgresql', 'PASSWORD': 'postgresl', 'HOST': 'localhost', 'PORT': '5432', } } #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "redsocial.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) python manage.py migrate, python manage.py test, python manage.py runserver enter image description here enter image description here enter … -
What is the correct way to catch model object deleted time in django?
signal CODE : @receiver(post_save, sender=TestModel) def update_log(sender, instance, **kwargs): TestModelLog.objects.create(description=instance.description, datetime=instance.updated) @receiver(post_delete, sender=TestModel) def delete_log(sender, instance, **kwargs): TestModelLog.objects.create(description=instance.description, datetime=now()) model CODE: class TestModel(models.Model): description = models.CharField(max_length=34) updated = models.DateTimeField(auto_now=True) I made signal code like above one and which is to catch log of TestModel. As you can see, I can get update time using instance as datetime=instance.updated. And it is correctly the same as TestModel's updated time. When I want to get deleted time, datetime=instance.updated is not working. So I tried to catch deleted time using datetime=now(). But I'm curious about that there is other good way except datetime=now(). Would you let me know other good way of catching object's deleted time? -
Persisted data with Django and Algolia search model indexing
This is a curious one for Django+Algolia. I'm using the Algolia specific Django package: $ pip install algoliasearch-django I have the following model schema: import os import datetime from channels import Group from django.db import models from django.conf import settings from django.utils.six import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.core.files.storage import FileSystemStorage from django.contrib.humanize.templatetags.humanize import naturaltime BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SITE_UPLOAD_LOC = FileSystemStorage(location=os.path.join(BASE_DIR, 'uploads/site')) USER_UPLOAD_LOC = FileSystemStorage(location=os.path.join(BASE_DIR, 'uploads/user')) @python_2_unicode_compatible class Room(models.Model): """ This model class sets up the room that people can chat within - much like a forum topic. """ title = models.CharField(max_length=255) staff = models.BooleanField(default=False) slug = models.SlugField(max_length=250, default='') banner = models.ImageField(storage=USER_UPLOAD_LOC, null=True, blank=True) def last_activity(self): """ For date and time values show how many seconds, minutes, or hours ago a message was sent (i.e., persised to the database) compared to current timestamp return representing string. """ last_persisted_message = Messages.objects.filter(where=self.slug).order_by('-sent_at').first() if last_persisted_message is not None: # First we can store "last persisted message" time in ISO format (could be useful for sitemap.xml generation; SEO tasks etc) last_persisted_message_iso = last_persisted_message.sent_at.isoformat() # Use the natural time package form contrib.humanize to convert our datetime to a string. last_persisted_message = naturaltime(last_persisted_message.sent_at) return last_persisted_message else: return "No activity to report" Which is … -
Autofill database column after form submission in django
Using Django 2.0 I have a model class named Book that asks for title, author, year but I have another column in that row that requires for a unique id based on the authors name, book title, and random numbers. This is my model class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=50) year = models.PositiveSmallIntegerField() identification = models.CharField(max_length=50, blank=True) holder = models.ForeignKey('Person', related_name='book_holder', on_delete=models.PROTECT(), null=True, blank=True) available = models.BooleanField(default=True, blank=True) overdue = models.BooleanField(default=False, blank=True) and it will be used in a form that only asks for the title, author, and year but what im looking for is how can i fill the identification column after the user submits the form. So for example if the user enters Harry Potter for the title and J. K. Rowling for the author, I want identification to have a value of a combination of both plus an eight digit random number at the end something like JH28194637 but I also need this column to be unique for every book so if i had to of the same Harry Potter books, I would need both to be different so one could be JH28194637 while the other one could be JH39287104. I will be using ajax …