Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Include external library without CDN
I have a Django project (git but not public yet) and I want to include a Javascript library that does not provide a CDN url. It should: Not be inside the Django project (eg. 'static' dir) Be pypi compatible What is the proper way to include this into my project? -
GCP App Engine deploy - Failed to build logilab-astng
I'm posting this to hopefully help anyone else with the same problem. I've used the GCP documentation to deploy my python application to GCP App Engine. I was getting the following failure with log out of: ERROR: build step 1 "gcr.io/gae-runtimes/python37_app_builder:python37_20190907_3_7_4_RC00" failed: exit status 1 ERROR Finished Step #1 - "builder" Step #1 - "builder": IOError: [Errno 2] No such file or directory: '""/output' Step #1 - "builder": File "/usr/local/bin/ftl.par/__main__/ftl/common/ftl_error.py", line 58, in UserErrorHandler Step #1 - "builder": File "/usr/local/bin/ftl.par/__main__.py", line 57, in main Step #1 - "builder": File "/usr/local/bin/ftl.par/__main__.py", line 65, in <module> Step #1 - "builder": exec code in run_globals Step #1 - "builder": File "/usr/lib/python2.7/runpy.py", line 72, in _run_code Step #1 - "builder": "__main__", fname, loader, pkg_name) Step #1 - "builder": File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main Step #1 - "builder": Traceback (most recent call last): Step #1 - "builder": error: `pip_download_wheels` returned code: 1 Step #1 - "builder": Step #1 - "builder": ERROR: Failed to build one or more wheels Step #1 - "builder": Failed building wheel for logilab-astng Step #1 - "builder": ERROR `pip_download_wheels` had stderr output: Step #1 - "builder": INFO full build took 24 seconds Step #1 - "builder": INFO build process for … -
How can create model that couldn't be changed by admin?
I need to create Django model that couldn't by admin, but he should be avialable to see it. It's content will be input from site. How can I do it? -
Serving Django and Vue with Nginx
I have a website which uses Django for the API and Vue for the frontend. Currently when I deploy the site I do the following: Create a production build of the Vue app (npm run build) Copy the Vue dist folder into a specific folder within the Django app One of the Django urls is setup as a TemplateView which serves up the Vue index.html By doing the above, Nginx in production simply serves up the Django app using gunicorn and everything works. However I would prefer to have Nginx serve up the Vue index.html and static files. This would allow me to create the Vue production build without any need for any changes on the Django side. Here is my current Nginx config: upstream appserver_wsgi_app { server localhost:8000 fail_timeout=0; } server { listen 80; server_name www.example.com; rewrite ^(.*) https://$server_name$1 permanent; } server { server_name www.example.com; listen 443 ssl; ... ... ... location /static { autoindex on; alias /home/user/static_django_files/; } location /media { autoindex on; alias /home/user/media_django_files/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request-filename) { proxy_pass http://appserver_wsgi_app; break; } } } What needs to be changed in Nginx? Also, does anything need … -
Django filter returning empty query set even though there is a match to data
I have a Django site, and am looking to filter my model for a specific field. The field, CreatedDate is a datetime field, and it is returning none, even though I am certain that the data I specify is in the query set. I have tried casting the user entered date to a datetime object, parsing through the query set and adding each models CreatedDate into a list, and then checking if the user entered date is in the list, which it is( this is how I know the data is there views.py if createdDate[0] == '>': createdDate = createdDate[1:] cd = datetime.strptime(createdDate, '%Y-%m-%d') try: query_results = query_results.filter(CreatedDate__gte=cd) except Exception as e: print2(e) elif createdDate[0] == '<': createdDate = createdDate[1:] cd = datetime.strptime(createdDate, '%Y-%m-%d') try: query_results = query_results.filter(CreatedDate__lte=cd) except Exception as e: print2(e) else: cd = datetime.strptime(createdDate, '%Y-%m-%d') try: print2(createdDate) print2(query_results) query_results = query_results.filter (CreatedDate__icontains=cd) except Exception as e: print2(e) models.py CreatedDate = models.DateTimeField(blank=True, null=True) Database - Column CreatedDate sample 2019-08-09 10:33:06.700 2019-08-09 10:33:06.700 2019-08-09 10:33:06.700 2019-09-27 00:00:00.000 2019-09-27 00:00:00.000 2019-09-27 00:00:00.000 I have no Idea why the filter is returning an empty query set, even though the dates that I enter are clearly in the database. If I am … -
jQuery validate with many select multiple fields (with Django)
My form has automatically generated multiselect fields. This means I don't know how many of them will be created (depends on input file). Also, select name cannot be used since its autogenerated in a specific way, so I guess in jQuery I'd have to go with either class or ID. I've already tried few options I found on stackoverflow etc, and the best of what I could get to was my code below. It actually validates if there is at least one option selected, but across all of presented multiselect fields. So if I have 10 fields, in one of them one was selected, thats enough for submit button to work, which is not what I want. Theres the jQuery part: <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script> $(function () { $('#myForm').submit(function () { var isValid = true; var form = this; isValid = isValid && validateMultipleSelect($('select.required', form)); return isValid; }); }); function validateMultipleSelect(select) { var number = $('option:selected', select).size(); alert("Select at least one option in each column per Vendor") return (number > 0); } Now this is the Form part: <form action="{% url 'index' %}" method="post" id="myForm"> {% csrf_token %} <p></p> <hr> {% for vendor in vendor_list %} {{ vendor.vendor_name }} … -
Error running WSGI application, ModuleNotFoundError: No module named 'django_countries'
I'm trying to deploy my webApp on PythonAnywhere but the following error occour: 2019-10-01 18:20:12,820: Error running WSGI application 2019-10-01 18:20:12,928: ModuleNotFoundError: No module named 'django_countries' 2019-10-01 18:20:12,928: File "/var/www/namesurname_pythonanywhere_com_wsgi.py", line 33, in <module> 2019-10-01 18:20:12,929: application = get_wsgi_application() 2019-10-01 18:20:12,929: 2019-10-01 18:20:12,929: File "/home/namesurname/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2019-10-01 18:20:12,929: django.setup(set_prefix=False) 2019-10-01 18:20:12,929: 2019-10-01 18:20:12,929: File "/home/namesurname/.virtualenvs/myenv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup 2019-10-01 18:20:12,929: apps.populate(settings.INSTALLED_APPS) 2019-10-01 18:20:12,930: 2019-10-01 18:20:12,930: File "/home/namesurname/.virtualenvs/myenv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate 2019-10-01 18:20:12,930: app_config = AppConfig.create(entry) 2019-10-01 18:20:12,930: 2019-10-01 18:20:12,930: File "/home/namesurname/.virtualenvs/myenv/lib/python3.7/site-packages/django/apps/config.py", line 90, in create 2019-10-01 18:20:12,930: module = import_module(entry) Django_countries is successfully already installed, I used the bash console of python anywhere. I also installed other third party modules, like django-allauth, but no error about those. Since I have no idea where to look, instead of posting a bunch of probably non-related codes I'll post on request. This is my first webapp I'm trying to deploy, so any help or hint is really appreciated, thanks. -
Following Django official tutorial part 2, makemigrations issue, not getting Add field question to choice
I got stuck on part 2 of the Django official tutorial while trying to makemigrations after editing models.py. https://docs.djangoproject.com/en/2.2/intro/tutorial02/#activating-models I got only these two lines: /mysite$ python manage.py makemigrations polls Migrations for 'polls': polls/migrations/0001_initial.py - Create model Question - Create model Choice Missing "- Add field question to choice" which later results in issues while I'm trying to add choices in Python shell. I have been copying most of the code, nevertheless my models.py is currently back to: from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) Is there anything I could do wrong there to not get this "- Add field question to choice" ? Later when I was trying to add the first choice to that question console told me that: >>> q = Question.objects.get(pk=1) >>> q <Question: What's up?> >>> q.choice_set.all() <QuerySet []> >>> q.choice_set.create(choice_text='Not much', votes=0) Traceback (most recent call last): File "/usr/lib/python3.6/code.py", line 91, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/home/rufus/.local/lib/python3.6/site- packages/django/db/models/base.py", line 519, in __repr__ return '<%s: %s>' % (self.__class__.__name__, self) File "/home/rufus/mysite/polls/models.py", line 19, in __str__ return self.question_text AttributeError: 'Choice' object has … -
IntegrityError at /add_contact/ NOT NULL constraint failed: contacts_contactcustomfield.custom_field_id
i my trying to submit my form but this error coming. i think my form data is not saved to the correct path.oiuodsijddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd views.py - my view file def addContact(request): if (request.GET): contact = Contact() contact.fname = request.GET['fname'] contact.lname = request.GET['lname'] contact.email = request.GET['email'] contact.mobile = request.GET['mobile'] contact.address = request.GET['address'] contact.pincode = request.GET['pincode'] contact.save() # contact.attribute.add(obj) for obj in Field.objects.all(): #contact.attribute.add(obj) custom_field = ContactCustomField() custom_field.contact = contact custom_field.custom_field = obj custom_field.custom_field_value = request.GET[obj.field_name] custom_field.save() print(request.GET[obj.field_name]) for obj2 in picklist.objects.all(): # contact.attribute.add(obj2) custom_field_picklist = ContactCustomField() custom_field_picklist.contact = contact custom_field_picklist.custom_field_picklist = obj2 custom_field_picklist.custom_field_value = request.GET[obj2.fieldname] custom_field_picklist.save() print(request.GET[obj2.fieldname]) messages.success(request, 'Contact Added Successfully') return redirect('add_contact') return render(request, 'add_contact.html', {'fields': Field.objects, 'fields2': picklist.objects}) mdoels.py- my model file my field model class Field(models.Model): field_name = models.CharField(max_length=100, unique=True) field_type = models.CharField(max_length=50) max_length = models.IntegerField(default=None) is_required = models.BooleanField() def __str__(self): return self.field_name class picklist(models.Model): fieldname = models.CharField(max_length=100, unique=True) isrequired = models.BooleanField() def __str__(self): return self.fieldname my contact model class Contact(models.Model): fname = models.CharField(max_length=200, null=True) lname = models.CharField(max_length=200, null=True) email = models.EmailField() mobile = models.IntegerField(max_length=10) address = models.CharField(max_length=200,default=None) pincode = models.IntegerField() created_date = models.DateField(auto_now=True) def name(self): return self.fname+" "+self.lname customfield model- class ContactCustomField(models.Model): custom_field = models.ForeignKey(Field, on_delete=models.CASCADE) custom_field_picklist = models.ForeignKey(picklist, on_delete=models.CASCADE) contact = models.ForeignKey(Contact, related_name='custom_data', on_delete=models.CASCADE) custom_field_value = models.TextField() … -
Error when trying to display a video in django
I'm trying to make a video display randomly on my homepage. A user is able to upload a video and it would be saved to a document in media/documents as well as to a dataset. I tried the code below and it keeps giving me an error, Exception Type: TemplateSyntaxError at / Exception Value: 'media' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache i18n l10n log static staticfiles tz I removed if settings.DEBUG: from urls.py and added .url to {% media 'doc.document.url' %}, however this didn't work. home.html {% load media %} {% for doc in document %} <video width='320' height= '240' controls> <source src="{% media 'doc.document.url' %}" type='video/mp4'> Your browser does not support the video tag. </video> {% endfor %} models.py from django.db import models from datetime import datetime from django.contrib.auth.models import User from django.conf import settings ... class Document(models.Model): title = models.CharField(max_length=100, default='NoTitle') description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField("date published")#(auto_now_add=True) creator = models.ForeignKey('auth.User', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.title urls.py urlpatterns = [ path('admin/', admin.site.urls), path("", views.homepage, name="homepage"), path("myconta/", views.myconta, name="myconta"), path("upload/", views.model_form_upload, name="upload"), path("register/", views.register, name="register"), path('', include("django.contrib.auth.urls")), ] #if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) … -
How to create a grouped QuerySet for use in ModelAdmin.get_queryset
I want to be able to display a list of banned ip addresses grouped by ip, sorted descending by count and the latest time of ban, as an admin changelist. fail2ban generates a sqlite-db and debian-8/fail2ban-debian-0.9.6 generates this table: "CREATE TABLE bans(" \ "jail TEXT NOT NULL, " \ "ip TEXT, " \ "timeofban INTEGER NOT NULL, " \ "data JSON, " \ "FOREIGN KEY(jail) REFERENCES jails(name) " \ ");" \ "CREATE INDEX bans_jail_timeofban_ip ON bans(jail, timeofban);" \ "CREATE INDEX bans_jail_ip ON bans(jail, ip);" \ "CREATE INDEX bans_ip ON bans(ip);" the SQL i would like django to produce should return the same results as this SQL: SELECT ip, strftime('%Y-%m-%d %H:%M:%S', timeofban, 'unixepoch', 'localtime') as latest, COUNT(ip) as ipcount FROM bans GROUP BY ip ORDER BY ipcount DESC, timeofban DESC So i started to set up the additional db in settings: DATABASES = { ... 'fail2ban': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/var/lib/fail2ban/fail2ban.sqlite3', } } DATABASE_ROUTERS = [ 'fail2ban.dbrouter.Fail2BanRouter' ] Created a model: from django.db import models class Ban(models.Model): jail = models.CharField('jail', max_length=250) ip = models.CharField('ip', max_length=100) timeofban = models.IntegerField('timeofban', primary_key=True) data = models.TextField('data', blank=True, null=True) class Meta: db_table = 'bans' ordering = ["-timeofban"] managed = False def save(self, **kwargs): raise NotImplementedError() Setup … -
How to join three tables through nested Serialization
I have to join 3 tables through nested serialization, 2 tables have their foreign key relation in a third table. these are the tables, class Product_Sales(models.Model): product_key = models.ForeignKey('Product',on_delete= models.CASCADE, null=True,related_name='productkey') channel_key = models.ForeignKey('Channel', on_delete= models.CASCADE, null=True,related_name='channelkey') outlet_key = models.ForeignKey('Outlet',on_delete= models.CASCADE, null=True,related_name='outletkey') sales_type = models.TextField(null=True) date = models.DateField(null=True) sales_units = models.IntegerField(null=True) sales_volume = models.IntegerField(null=True) sales_amt = models.DecimalField(null=True,max_digits=8, decimal_places=3) sales_to = models.TextField(null=True) sales_from = models.TextField(null=True) objects = models.Manager() objects=CopyManager() class Outlet(models.Model): outlet_key = models.AutoField(primary_key=True) outlet_group = models.TextField(null=True) outlet_company = models.TextField(null=True) outlet = models.TextField(null=True) objects = models.Manager() objects=CopyManager() class Channel(models.Model): channel_key = models.AutoField(primary_key=True) channel = models.TextField(null=True) objects=CopyManager() serializer.py class ModelMappingSerializer(WritableNestedModelSerializer): outletkey=OutletSerializer(many=True,read_only=True) channelkey=ChannelSerializer(many=True,read_only=True) class Meta: model = Product_Sales fields = ['product_key','channel_key','outlet_key','sales_type','date','sales_units','sales_volume','sales_amt','sales_from','sales_to','sales_from','outletkey','channelkey'] Output on Postman [{ "product_key": 1, "channel_key": 1, "outlet_key": 1, "sales_type": null, "date": "2019-09-05", "sales_units": 22, "sales_volume": 11, "sales_amt": "409.480", "sales_from": null, "sales_to": null }] it is not including the fields of Outlet and Channel tables -
class Person(models.Model) why variable models can be used inside the class
I am a beginner of python and I have a question when I learn django, hope someone can help. (pls correct me if comments below is wrong) python document was read from django.db import models # this line is to import package of models class Person(models.Model): # this is to indicate Person inheritance of parent class Model, Model is the class name first_name = models.CharField(max_length=30) question is here: is "model" the package name, why it can be used this way models.CharField? can pls anyone explain? thanks a lot -
Searching Pages and custom models at the same time in Wagtail
I made a blunder - implemented some models in our application as plain Django models (but Indexable) instead of Page models. Now the client would like to see a unified search results page (so a faceted search is not adequate)... so I am completely stuck. We are using the PostgreSQL backend. The s.search() function requires a model or queryset; and you cannot combine PostgresSearchResults query sets. If I convert the 2 result sets to list and combine them I lose the relevancy of the results. Any ideas? -
Django migration cannot assign User instance to user field
Problem Recently I created a new migration for a SubscriptionAccount model which replaces an email field with a link to the User model. In this migration I also do a small data migration which fetches the users with the email and sets it to the SubscriptionAccount.user. However, for some reason the migration does not want to assign the user to the newly created user field. Complaining that it cannot assign a User instance ant that it expects a User instance. Which is weird, because that's exactly what I'm doing. Error The following error occurs: Traceback (most recent call last): File "./manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/operations/special.py", line 193, in database_forwards self.code(from_state.apps, schema_editor) File "/project/hypernodedb/migrations/0069_link_subscription_account_to_user.py", … -
ValidationError: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."] in django
when I initiate the request for the date field name as dob with the respective value of dob is "dob":"1996-10-25" Model.py class Register_model(models.Model): UserId = models.CharField(max_length=255,default='',blank=True,null=True) ISpinId = models.CharField(max_length=255,primary_key=True, unique=True,default='', blank=True,null = False) email = models.CharField(max_length=250, unique=True) first_name = models.CharField(max_length=250, default="",null = False) last_name = models.CharField(max_length=250, default="",null = False) dob = models.DateField(auto_now_add=False, auto_now=False) password = models.CharField(max_length=255,blank=False,null = False) gender = models.CharField(max_length=50,default="",null = False) nationality = models.CharField(max_length=100,default="",null = False) views.py @permission_classes((AllowAny,)) class User_RegisterAPIViews(APIView): # Serializer Initilization print("dasf") serializers = serializers.Register_Serializer # Post method Declarations def post(self, request): request.POST._mutable = True print(request.data) request.data['ISpinId'] = etc.random_number_generate(request.data['first_name'], request.data['last_name']) password = request.data['password'] print(request.data['dob']) playersCategory, age = etc.age_convert(request.data['dob'], request.data['gender']) request.data['players_category'] = playersCategory request.data['age'] = age form_data = serializers.Register_Serializer(data=request.data) if form_data.is_valid(): print("formdata",form_data) form_data.save() # File Save Error : Traceback (most recent call last): File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/rest_framework/views.py", line 497, in dispatch response = self.handle_exception(exc) File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/rest_framework/views.py", line 457, in handle_exception self.raise_uncaught_exception(exc) File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/rest_framework/views.py", line 468, in raise_uncaught_exception raise exc File … -
Running a scheduled zappa function manually
I want to test the event in zappa_settings.json locally I have set up the environment and I have the server running a Django site on my local machine, I am also able to deploy the Django site to AWS via Zappa. Before pushing it to the cloud I would like to test the event which is used to deploy a cronjob to the cloud with Lambda functions. I keep getting errors on the imports. Here is my Event in zappa_settings.json "events": [{ "function": "main.kpi_report.auto_scraper", "expression": "cron(20 12 * * ? *)" // "expression": "rate(10 minutes)" }], Here are the imports in my kpi_report.py file from .mws_settings import mws_settings from .util import get_country_by_marketplace_name, date_amz_to_normal, process_currency from .dynamodb import KPI Python3 manage.py runserver System check identified no issues (0 silenced). You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. October 03, 2019 - 12:23:46 Django version 2.0.7, using settings 'com.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Then finally when I run the auto_scrapper manually on my local machine: t$ python main/kpi_report.py auto_scrapper Traceback (most recent call last): File … -
How can I pass content between apps in django?
My current project is composed to two apps. One is a kind of catalog of products. The other is a blog. The product catalog app is pointed to the main or index page. I want to add a side bar on there where the new blog posts from the other app will appear. This is what I have so far. Can someone tell me what I am doing wrong? Views from blog.models import Post def index(request): Transmitters = reversed(Album.objects.all()) receiver = reversed(Receiver.objects.all()) posts = (Post.objects.all()) context = {'Transmitters': Transmitters , 'Receivers': receiver, 'Post': posts} return render(request, 'music/index.html', context) URLs urlpatterns = [ # /index/ url(r'^$', views.index, name='index'), ] HTML <div class="container container-fluid"> {% for post in posts %} <article class='media content-section'> <img class='rounded-circle article-img' src='{{ post.author.profiles.image.url }}'> <div class='media-body'> <div class='article-metadata'> <br>Published by <b>{{ post.author |capfirst}}</b> | <small class='text-muted'>{{ post.created }}</small> </div> <h2><a class='article-title' href="{{ post.get_absolute_url }}"><b>{{ post.title }}</b></a></h2> <p class="lead"> {{post.body|safe|truncatewords:80}} </p> </div> </article> {% endfor %} </div> -
How to translate whole html page in another language in Django?
Currently I am developing website using Django framework & I have to translate my web page into another language (French) & all other pages are in English language. <html lang="fr"> I have set like above but code not working & getting page in English language only. -
Implementing LEFT JOIN explicitly in Django
I have been thru endless posts on Django and the LEFT JOIN problem and but have not found anyone that has a solution in the 2.2 version of Django. Whilst in years past it seems there were ways to get around this problem, the Django team seem to have shut down every mechanism people have employed to achieve the most simple but necessary query - the LEFT JOIN. Here is a simle example of what I am trying to do (it is a simple example to reflect a real world scenario so please do not offer ways to redesign the models... all I want is the age old LEFT JOIN in SQL .... that simple): from django.db import models from uuid import uuid4 class People(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid4) name = models.CharField(max_length=255) class Book(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid4) name = models.CharField(max_length=255) author = models.ForeignKey(People) publisher = models.ForeignKey(People, on_delete=models.PROTECT, null=True) How would I achive an output showing all books and the publisher if there is a publisher (otherwise just blank) Books.objects.filter(Q(publisher__isnull=True | Q(publisher__isnull=False) ... produces an INNER JOIN which will obviously only show books that have a publisher assigned. The query I am looking for would be of the … -
how to add new column to model which is referenced to other model by foreign key in django
I have a model named Shape: class Shape(models.Model): name = models.CharField(max_length=40, unique=True) and another model named Tank which has Shape model as foreignkey: def get_default(model): value, is_created = model.objects.get_or_create(name=0) return value.id class Tank(models.Model): name = models.CharField(max_length=50) shape = models.ForeignKey(Shape, on_delete=models.SET_DEFAULT, default=get_default(Shape), related_name="tanks") when i try to add a new column(with null=True) in Shape model, at python manage.py makemigrations django raises a error: django.db.utils.OperationalError: no such column: tank_shape.Column name -
Django AJAX library
I am trying to implement django_ajax library(https://github.com/yceruto/django-ajax) in my project. So, this example works fine: #views.py from django.http import HttpResponse from django.shortcuts import render from django.views.generic.edit import FormView from django.views.generic.base import TemplateView from django.urls import reverse_lazy from django_ajax.mixin import AJAXMixin from .forms import NameForm class NameView(FormView): template_name = 'postajax.html' form_class = NameForm success_url = reverse_lazy('myapp:success') def form_valid(self, form): return super().form_valid(form) class SuccessView(AJAXMixin, TemplateView): template_name = 'success.html' def __init__(self, **kwargs): super().__init__(**kwargs) self.ajax_mandatory = False #postajax.html <!DOCTYPE html> <html id="successhtml"> <head> <title>Page Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <form action="" method="post" id="frm"> {% csrf_token %} {{ form.as_p}} <input type="submit" value="Submit"> </form> <script> var frm = $('#frm'); frm.unbind('submit').submit(function () { $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { console.log(data) $('#successhtml').html(data.content) }, error: function(data) { alert("Something went wrong") } }); return false; }); </script> </body> </html> the response is: { content: "<!DOCTYPE html>\n<html>\n<head>\n<title>Page Title</title>\n</head>\n<body>\n\n\n<p>Success</p>\n\n</body>\n</html>", status: 200, statusText: "OK" } everything is oke. My real project structure (where i want to implement AJAXMixin) looks something like this: #views.py class MyView(AJAXMixin, FormView): def get(self, request, *args, **kwargs): response = super().get(request, *args, **kwargs) . . retrurn response def form_valid(self, form): . . . . return super().form_valid(form) def get_success_url(self): return reverse(...) I skipped the non-relevant lines. … -
Save GEOJSON file to database
In my templates form, i have a script where the loggedin user can draw a polygon and export it as a geojson. I would like to save this drawn polygon to the database. I have created a model : plot = models.PolygonField() But i don't know how to pass this export to the plot -
Sidebar / Navbar in Django
How can I create a Django project with a fixed sidebar that rarely change? Currently on every page I visit, whole page is reloaded which means sidebar too. It is kinda irritating. Thanks in advance! -
Django Time Series Data - Handling multiple CSVs
I am working on a homework related to Django framework. The problem is the following: I was provided with a .csv file containing patients' record: 1- Name 2- Age 3- Weight Each patient also has a separate .csv file, containing hundreds of data points for the patient blood pressure (timestamp every 20 minutes). So I assume I need to add 2 more variables: 4- Datetime variable that captures the time 5- Blood Pressure (BOTH 4 AND 5 ARE TIME SERIES AS DESCRIBED ABOVE) As a first step I need to load the user data through django. The Problem is: 1) For the first 3 variables, I would create a model form defining each variable with its corresponding type (say charfield()). For the blood pressure and the Datetime, what is the most efficient way to proceed? (PS: I AM USING DJANGO 1.11) 2) The files should be loaded using a django Management Command File(.py file). What is the most efficient way to load all the .csv files into the django framework? (I have 1 file containing all the patients with their age and name, and each patient has a separate .csv file with the blood pressure records).