Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Maintaining Relationships Between Models that are Filled Through Signals After Saving
I have a base model called stars that contains most relationships with other models, and some of the other models are taken through a signal to perform certain scripts that will enter into the database more information about the base model. My problem is when running the signals, I don't know how to maintain relationships with the models that are already a one to one field of the base model. If I try to make the empty models used for a signal a foreign key of their instance, it gives me errors since their instance is already connected to stars through its own foreign key. I'll post my code here, first models, and then the signal: from django.db import models # Create your models here. '''define table with star name and its found relationships in the cards''' class Star(models.Model): name = models.CharField(max_length=100, unique = True, verbose_name = "Star Name") def __str__(self): return self.name class ReferenceURL(models.Model): URL = models.URLField(help_text="<h3> Link to the ADS reference search, and perform a search on the reference. </br> Click the link to the corresponding paper and copy the URL of said paper: </br> <a href='http://adsabs.harvard.edu/abstract_service.html' target='_blank'>LINK TO ADS SEARCH. </a> </br> A typical link should look … -
Docker with Angular 4 and Django is compiled successfully but localhost:4200 is not working
I would like to dockerize Angular 4 frontend with Django backend and postgresql database. At this moment my files looks as shown below. I am note sure if this is done properly? When I try docker-compose up I get information that both frontend with Angular 4 and backend with Django started successfully. Unfortunately when I open http://localhost:4200 it doesn't work (localhost:8001 seems working): django_1 | Django version 1.11, using settings 'pri.settings' django_1 | Starting development server at http://0.0.0.0:8001/ django_1 | Quit the server with CONTROL-C. angular_1 | ** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 ** angular_1 | Hash: e558fb64115f711b26a4 angular_1 | Time: 20657ms angular_1 | chunk {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 232 kB {4} [initial] [rendered] angular_1 | chunk {1} main.bundle.js, main.bundle.js.map (main) 222 kB {3} [initial] [rendered] angular_1 | chunk {2} styles.bundle.js, styles.bundle.js.map (styles) 11.6 kB {4} [initial] [rendered] angular_1 | chunk {3} vendor.bundle.js, vendor.bundle.js.map (vendor) 4.41 MB [initial] [rendered] angular_1 | chunk {4} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered] angular_1 | webpack: Compiled successfully. Structure of my files: ├── Backend │ ├── AI │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── settings.cpython-36.pyc … -
how to categorize the model under another model (e.i) rock ,Country, Blues, and Pop
from django.db import models from django.core.urlresolvers import reverse from django.conf import settings from django.contrib.auth.models import User class Album(models.Model): creator = models.CharField(max_length=250) album_name = models.CharField(max_length=250) category = models.CharField(max_length=250) album_photo = models.FileField() author = models.ForeignKey (User,on_delete=models.CASCADE, related_name='album', default='1') def get_absolute_url(self): return reverse('post:detail',kwargs={'pk': self.pk}) def __str__(self): return self.creator + ' - ' + self.album_name class Song(models.Model): Album = models.ForeignKey(Album, on_delete=models.CASCADE) song_name = models.CharField(max_length=250) def __str__(self): return self.song_name I would like to have another model to import all of my albums in which would take multiple categories. I am not sure how to start and everything i have tried has been useless -
How can I enable the users delete only the objects they create in Django?
They can do a bypass for a link by putting the post ID. I do not know how to solve it. /borrar/id Template button: {% if user == post.user %} <a class="close pull-right" href="{% url 'post_borrar' post.id %}"><span aria-hidden="true">&times;</span></a> {% endif %} Template posts/posts_mod_borrar.html: <form method="post"> {% csrf_token %} ¿Estás seguro que deseas borrar el post "{{ object }}"? <input type="submit" value="Submit" /> </form> views.py class PostDeleteView(generic.DeleteView): model = Post template_name = 'posts/posts_mod_borrar.html' success_url = reverse_lazy('timeline') model.py class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) texto = models.CharField(max_length=200) imagen = models.ImageField(upload_to='posts', blank=True) video = models.URLField(blank=True) creado = models.DateTimeField(auto_now_add=True) actualizado = models.DateTimeField(auto_now=True) class Meta: ordering = ["-creado"] def __str__(self): return self.texto -
Using Django template inside handlebar
Is there any way to use the Django template tag inside Handlebar? {{#location}} <div class="loc-name">{{name}}</div> <div>{{address}}</div> <div>{{address2}}</div> <!-- django templatetag here --> {% %} {{/location}} Thank you -
Websocket disconnects immediately after connecting (repeatedly)
I followed this tutorial: https://github.com/jacobian/channels-example And I got the error in the title, then I cloned the repository above and got the same error. (If you are trying to clone the repository to test, remember to change the database settings in settings.py, migrate the database, and go into views and change the import haikunator to from haikunator import Haikunator and in the new_room function add the line haikunator = Haikunator() to the beginning of the function so that it will work) I am using Python 2.7 ad Django 1.10. ' Traceback: System check identified no issues (0 silenced). July 06, 2017 - 13:22:20 Django version 1.10, using settings 'chat.settings' Starting Channels development server at http://127.0.0.1:8000/ Channel layer default (asgi_redis.core.RedisChannelLayer) Quit the server with CTRL-BREAK. 2017-07-06 13:22:20,969 - INFO - worker - Listening on channels http.request, websocket .connect, websocket.disconnect, websocket.receive 2017-07-06 13:22:20,971 - INFO - worker - Listening on channels http.request, websocket .connect, websocket.disconnect, websocket.receive 2017-07-06 13:22:20,973 - INFO - worker - Listening on channels http.request, websocket .connect, websocket.disconnect, websocket.receive 2017-07-06 13:22:20,977 - INFO - worker - Listening on channels http.request, websocket .connect, websocket.disconnect, websocket.receive 2017-07-06 13:22:20,986 - INFO - server - HTTP/2 support not enabled (install the http2 and tls … -
Python/Django recursion issue with saved querysets
I have user profiles that are each assigned a manager. I thought using recursion would be a good way to query every employee at every level under a particular manager. The goal is, if the CEO were to sign in, he should be able to query everyone at the company - but If I sign on I can only see people in my immediate team and the people below them, etc. until you get to the low level employees. However when I run the following: def team_training_list(request): # pulls all training documents from training document model user = request.user manager_direct_team = Profile.objects.filter(manager=user) query = Profile.objects.filter(first_name='fake') trickle_team = manager_loop(manager_direct_team, query) # manager_trickle_team = manager_direct_team | trickle_team print(trickle_team) def manager_loop(list, query): for member in list: user_instance = User.objects.get(username=member) has_team = Profile.objects.filter(manager=user_instance) if has_team: query = query | has_team manager_loop(has_team, query) else: continue return query It only returns the last query that was run instead of the compiled queryset that I am trying to grow. I've tried placing 'return' before 'manager_loop(has_team, query) in order save the values but it also kills the loop at the first non-manager employee instead of continuing to the next employee. I'm new to django so if there is … -
Django image does not display in template
I am using Django and i want to import an image to my about.html file Both the picture and the about.html are in the same file, see the picture down i am trying to insert the image like this, but i get a broken picture icon <img src="templates/WebApp/rolomatik_logo_crna_verzija.png" Any suggestions please? -
1064, "You have an error in your SQL syntax MySQL server version for the right syntax to use near '1select f.name
I am getting this error in django when I am trying hit mysql database. but when I ran this query in db I got proper result my query is like "select f.name,scheduleDepart.depart_time,scheduleArrive.arrival_time,ai.name from flight as f,airline as ai,flight_schedule as scheduleDepart inner join flight_schedule as scheduleArrive on scheduleDepart.flight_id=scheduleArrive.flight_id where scheduleArrive.location_id=%d and scheduleDepart.location_id=%d and scheduleArrive.flight_id=f.id and f.airline_code_id=ai.id;""".join(''.join(elems) for elems in data) this is my stack trace raceback (most recent call last): File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\kepsla-workspace\WS\demoWS\flightBooking\booking\views.py", line 30, in flightBooking and scheduleArrive.flight_id=f.id and f.airline_code_id=ai.id;""".join(''.join(elems) for elems in data)) File "C:\Program Files (x86)\lib\site-packages\django\db\backends\utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Program Files (x86)\lib\site-packages\django\db\backends\utils.py", line 65, in execute return self.cursor.execute(sql, params) File "C:\Program Files (x86)\lib\site-packages\django\db\utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Program Files (x86)\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Program Files (x86)\lib\site-packages\django\db\backends\utils.py", line 63, in execute return self.cursor.execute(sql) File "C:\Program Files (x86)\lib\site-packages\django\db\backends\mysql\base.py", line 101, in execute return self.cursor.execute(query, args) File "C:\Program Files (x86)\lib\site-packages\MySQLdb\cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "C:\Program Files (x86)\lib\site-packages\MySQLdb\connections.py", line … -
Making a multiple field search in Django
I am trying to make a search page that searches for model objects using three fields corresponding to different pieces of data. Here is my code below: models.py class Schedules(models.Model): course_name = models.CharField(max_length=128, choices=COURSE_NAME_CHOICES, default='a-plus') start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today) instructor = models.CharField(max_length=128, choices=INSTRUCTOR_CHOICES, default='adewale') views.py def search_Schedule(request): context_dict = {} if request.method == 'POST': query1 = request.POST['course_name_search'] query2 = request.POST['start_date_search'] query3 = request.POST['instructor_search'] if query1: results = Schedules.objects.filter(course_name__icontains=query1) if query2: results = results.filter(start_time=query2) if query3: results = results.filter(instructor__icontains=query3) table = ScheduleTable(results) if results.count(): context_dict['table'] = table else: context_dict['no_results'] = query1 + ", " + query2 + ", and " + query3 else: table = ScheduleTable(results) if results.count(): context_dict['table'] = table else: context_dict['no_results'] = query1 + " and " + query2 elif query3: results = results.filter(start_time__icontains=query3) table = ScheduleTable(results) if results.count(): context_dict['table'] = table else: context_dict['no_results'] = query1 + " and " + query3 else: table = ScheduleTable(results) if results.count(): context_dict['table'] = table else: context_dict['no_results'] = query1 elif query2: results = Schedules.objects.filter(start_time=query2) if query3: results = results.filter(instructor__icontains=query3) table = ScheduleTable(results) if results.count(): context_dict['table'] = table else: context_dict['no_results'] = query2 + " and " + query3 else: table = ScheduleTable(results) if results.count(): context_dict['table'] = table else: context_dict['no_results'] = query2 elif query3: … -
error page while deploying first django app on pythonanywhere
i am getting error while deploying my first django app on pythonanywhere. it displays the error page says "something went wrong". i ran my code on local computer and it works fine. As suggested,i also checked errorlog page on pythonanywhere but it displays nothing(empty page). if anyone could help me with this ? Thanks. -
Django Oscar Stores - 'function' object has no attribute '_meta'
I am trying to get django-oscar-stores to work with Django v1.11. I have made multiple changes so far, but now I am stuck. I get this error whenever I click the link to create a new store front within the Django dashboard: 'function' object has no attribute '_meta' Here is the traceback: Environment: Request Method: GET Request URL: http://localhost:8000/dashboard/stores/create/ Django Version: 1.11.3 Python Version: 3.6.1 Installed Applications: ['django.apps.registry', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'django.views', 'widget_tweaks', 'stores', 'django.contrib.gis', 'oscar', 'oscar.apps.analytics', 'oscar.apps.checkout', 'oscar.apps.address', 'oscar.apps.shipping', 'oscar.apps.catalogue', 'oscar.apps.catalogue.reviews', 'oscar.apps.partner', 'oscar.apps.basket', 'oscar.apps.payment', 'oscar.apps.offer', 'oscar.apps.order', 'oscar.apps.customer', 'oscar.apps.promotions', 'oscar.apps.search', 'oscar.apps.voucher', 'oscar.apps.wishlists', 'oscar.apps.dashboard', 'oscar.apps.dashboard.reports', 'oscar.apps.dashboard.users', 'oscar.apps.dashboard.orders', 'oscar.apps.dashboard.promotions', 'oscar.apps.dashboard.catalogue', 'oscar.apps.dashboard.offers', 'oscar.apps.dashboard.partners', 'oscar.apps.dashboard.pages', 'oscar.apps.dashboard.ranges', 'oscar.apps.dashboard.reviews', 'oscar.apps.dashboard.vouchers', 'oscar.apps.dashboard.communications', 'oscar.apps.dashboard.shipping', 'haystack', 'treebeard', 'sorl.thumbnail', 'django_tables2'] Installed Middleware: ('django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'oscar.apps.basket.middleware.BasketMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware') Traceback: File "/home/noub/.virtualenvs/versishop/lib64/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/noub/.virtualenvs/versishop/lib64/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/home/noub/.virtualenvs/versishop/lib64/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/noub/.virtualenvs/versishop/lib64/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/noub/.virtualenvs/versishop/lib64/python3.6/site-packages/oscar/views/decorators.py" in _checklogin 33. return view_func(request, *args, **kwargs) File "/home/noub/.virtualenvs/versishop/lib64/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/noub/.virtualenvs/versishop/lib64/python3.6/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/home/noub/.virtualenvs/versishop/lib64/python3.6/site-packages/extra_views/advanced.py" in get 122. return super(BaseCreateWithInlinesView, self).get(request, *args, **kwargs) File … -
sequence item 0: expected str instance, bytes found
This question has been asked before but I am not getting where I went wrong. basically I have one many to many table. and am executing complex query on that so I have written views.pay like this def flightBooking(request): if request.method=='POST': form= SearchForm(request.POST) if not form.is_valid(): return render(request, 'booking/search.html',{'form':form}) else: form.is_valid() data=(form.cleaned_data['fromLocation'],form.cleaned_data['toLocation']) cursor=connection.cursor() cursor.execute("""select flight.name,scheduleDepart.depart_time,scheduleArrive.arrival_time.ai.name from flight flight,airline ai,flight_schedule scheduleDepart inner join flight_schedule scheduleArrive on scheduleDepart.flight_id=scheduleArrive.flight_id where scheduleArrive.location_id=%d and scheduleDepart.location_id=%d, and scheduleArrive.flight_id=flight.id and flight.airline_code_id=ai.id """,[data]) results=dictFetchAll(cursor) return render(results,'booking/searchResult.html') #return HttpResponse(results,'booking/searchResult.html') def dictFetchAll(cursor): "return all rows with column name" columns=[col[0] for col in cursor.description] return [ dict(zip(columns,row)) for row in cursor.fetchall() ] here my from and to location is integer field and I got stack trace like this File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Program Files (x86)\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\kepsla-workspace\WS\demoWS\flightBooking\booking\views.py", line 29, in flightBooking and scheduleArrive.flight_id=flight.id and flight.airline_code_id=ai.id """,[data]) File "C:\Program Files (x86)\lib\site-packages\django\db\backends\utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Program Files (x86)\lib\site-packages\django\db\backends\utils.py", line 65, in execute return self.cursor.execute(sql, params) File "C:\Program Files (x86)\lib\site-packages\django\db\backends\mysql\base.py", line 101, in execute return self.cursor.execute(query, args) File "C:\Program … -
Django-haystack with elastic-search is not giving search results for some model Indexes, while giving the search result for some model Indexes
I am working on a django project(community-like-site) in which I have to build a search engine for the site. I am using Django and elasticsearch 1.4.. and there is some problem when I am using the default SearchView of Haystack. I have checked and all my items are indexed properly. However, while searching, some of the model Indexes are providing results while others are not. What I mean is that my models.py look something like this. import uuid from django.contrib.auth.models import User from django.core.serializers import serialize from django.db import models # Create your models here. class UserCredentials(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) password = models.CharField(max_length=50, blank=True) email = models.EmailField(blank=True, null=True,unique=True) mobile_number = models.CharField(max_length=20, null=True, blank=True,unique=True) is_verify_mobile = models.BooleanField(default=False, blank=False) is_verify_email = models.BooleanField(default=False, blank=False) loginthrough = models.CharField(max_length=20, null=True, blank=True,default="normal") # google , linkedin , normal otp = models.IntegerField(null=True,blank=True) class UserProfile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) userId = models.ForeignKey(UserCredentials, on_delete=models.SET_NULL, null=True, blank=True) first_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(blank=True, null=True, unique=True) mobile_number = models.CharField(max_length=20, null=True, blank=True, unique=True) gender = models.CharField(max_length=20, choices=(('M', 'male'), ('F', 'female'), ('O', 'others'))) date_of_birth = models.DateTimeField(null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) state = models.CharField(max_length=100, null=True, blank=True) zipcode = … -
Django rest api: how to return a JsonArray of jsonObjects as a model filed?
I have two django models as shown model 1 class Big(models.Model): name = models.CharField(max_length=50, null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) model2 class Small(models.Model): big = models.ForeignKey(Big, related_name='small',null=True,on_delete=models.CASCADE) There can be more than one Small items inside a Big item. The Bigserializer looks like below class BigSerializer(serializers.ModelSerializer): class Meta: model = Hotel fields = ('name','small') Now on accessing the Big items,i am getting name and small fields. But the small field returns only the id of the Small model. I need the whole details like name and address of small item inside the small field. How could i achieve it? -
Django App Instances?
I am hoping you might be able give me some guidance on a project and the best way to tackle it. The Goal: Create temporary chatrooms, then delete the relevant data upon closing. My Take: I have a functional Django App for the chatroom, and am thinking about creating dynamic instances of it for each chatroom. With this method, I hope to generate a new room when needed, and then drop/clear the tables once the room is closed. My Questions: I saw a couple other posts relating to this topic, and wanted a few opinions. My goal is to have a faster site that runs on little resources, and also value the anonymity of it. Am I going about this the right way, or is there a better way to do this? -
"This field is required" when field is populated on Django modelForm
After clicking the upload button on a form I get a bullet point beneath the 'Job ID' field stating "This field is required." even though I have values enterred into the field. Here is my code: forms.py: class UploadFileForm(forms.ModelForm): class Meta: model = Job fields = ['jobID', 'original_file'] labels = { 'jobID': _('Job ID'), 'original_file': _('File'),} error_messages = { 'jobID': {'max_length': _("Job ID is limited to 50 characters."), }, NON_FIELD_ERRORS: { 'unique_together': "%(model_name)s's %(field_labels)s are not unique.", } } models.py: from __future__ import unicode_literals from django.db import models from django.utils import timezone class Job(models.Model): user = models.ForeignKey('auth.User') original_file = models.FileField() jobID = models.CharField(max_length=50) rev = models.IntegerField() create_date = models.DateTimeField(default = timezone.now) def save(self): "Get last value of rev considering jobID and User and increment" "see https://stackoverflow.com/questions/1065089/auto-increment-a-value-in-django-with-respect-to-the-previous-one" last_rev = Job.objects.filter(user=self.user).filter(jobID=self.jobID).order_by('-rev') if last_rev: rev = last_rev[0].rev + 1 else: rev = 1 super(Job,self).save() def __unicode__(self): return self.jobID + " rev " + str(self.rev) class Meta: indexes = [ models.Index(fields=['user','jobID']), ] unique_together = ("user","jobID","rev") ordering = ['-create_date'] views.py from future import unicode_literals from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import UploadFileForm from .models import Job # Create your views here. def upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) … -
How do I stop formset from deleting values I keep zero
So, the default value of some integer fields in a one-to-many relationship model is zero. And if I don't edit them nd save the form, the values get deleted. Please guide me. I can't find anything related to this. Thank you. -
Django models update when backend database updated
I am relatively new to Django. I have managed to create a basic app and all that without problems and it works fine. The question probably has been asked before. Is there a way to update existing Django models already mapped to existing databases when the underlying database is modified? To be specific, I have mysql database that I use for my Django app as well as some standalone python and R scripts. Now, it is much easier to update the mysql database with, say, daily stock prices, everyday from my existing scripts outside Django models. Ideally, what I would like is to have my Django models that are already mapped to these tables to reflect the updated data. I know there is $ python manage.py inspectdb for creating models from existing databases. But that is not the objective. From what I have gathered so far from the docs and online searches, it is imperative to update the backend database through Django models. Not outside of it. Is it the case really? As long as the table structure doesn;t change I really don't see the why this should not be allowed. Database is meant to serve multiple customers isn't it? … -
represent a model and view using django framework?
I am working Django for the first time and I am trying to to represent a model and view for below question: Create models which represent: Author: Id, first_name, last_name, dob, email_address, and phone_number. All fields are required except phone_number. Book: Id, title, published_date, prices, authors. All fields are required. One book can have several authors. And I came up with below models? Since I am still a begineer so I might be off somewhere.. class Author(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) dob = models.CharField(max_length=20) email_address = models.CharField(max_length=100) phone_number = models.CharField(max_length=100) class Book(models.Model): id = models.CharField(max_length=20) title = models.CharField(max_length=20) published_date = models.DateTimeField(default=timezone.now) prices = models.CharField(max_length=100) author = models.CharField(max_length=100) Now I am confuse how I can write a view to list all the books based on above models? Also I need to create a template to list all books with the following condition: Book authors should display author’s name (first name and last name) Published date should be in format - Dec-21-2016 -
xxx.mhtml file can't display in my website
I'm writing a website with django. There are some xxx.mhtml document in my database. I want to show these document through my website. But it can't display normally. I write my code like this: static_mhtml is the relative path of my xxx.mhtml document. return render(request, static_mhtml) But with the same method: return render(request, static_html) static_html is the relative path of my xxx.html document. The html can display normally. How can i solve this problem? By the way, the .mhtml document can display in the Chrome in my desktop if i click it directly. Is there any method to open a local document, the URL may like file:///xxx.mhtml,throuth my website which the URL may like http://127.0.0.1:8000/page/xxxx. Or how to change my mhtml document to other format such as html、image and other format that can display in my website. -
Custon DjangoTemplates for one app
I want to use a third party app that did not use adequate django principles: templates \w hard coded urls instead of {% url ... %} syntax templates \w hard coded static files instead of {% static ... %} syntax makemigrations is left to the user/deployer all templates directly in templates folder, like 500.html, login.html, etc interesting nested app-structure, where some apps are loaded depending on the configuration (i.e. advanced settings.py logic manipulating INSTALLED_APPS) These make it hard to include the app in urls /suburl/.... I spent 15 minutes thinking this was rewritable, and a git PR would be a good idea, after realizing it might not be. Since the most crucial problem, hard coded urls, is in the templates, want to copy the templates to my parent-project in a subfolder, fix them with generated urls, and redefine template-resolution for this particular app, but not for all apps. This should keep my template-namespace relatively clean. Can I do this, define a customized DjangoTemplates for ONE specific app, but not the others? -
Two table filter
I try to filter the Author with the class Book that has the specific category, but I can't get the exact category. models.py class Book(models.Model): category = models.IntegerField() foreignkey = models.ForeignKey(Author, related_name="auth") class Author(models.Model): author_id = models.IntegerField(primary_key=True) views.py book = models.Book.objects.filter(category = 'Space') author = models.Author.objects.filter(author_id__in = book ) -
Dockerization and deploying on Heroku project with Angular 4 frontend with Django backend and postgresql database
I would like to dockerize Angular 4 frontend with Django backend and postgresql database. Besides, I am going to deploy it on Heroku. At this moment my situation looks as shown below. I am note sure if this is done properly? Unfortunately it doesn't work. When i try docker-compose up I get: MacBook-Pro:~ myUser$ docker-compose up Building angular Step 1/7 : FROM node:8.1.2-onbuild as builder # Executing 5 build triggers... Step 1/1 : ARG NODE_ENV ---> Using cache Step 1/1 : ENV NODE_ENV $NODE_ENV ---> Using cache Step 1/1 : COPY package.json /usr/src/app/ ---> Using cache Step 1/1 : RUN npm install && npm cache clean --force ---> Using cache Step 1/1 : COPY . /usr/src/app ---> Using cache ---> 4ba35205484c Step 2/7 : ARG TARGET=production ---> Using cache ---> 20f3f25f3d45 Step 3/7 : RUN npm install @angular/cli ---> Using cache ---> 005a5afcef88 Step 4/7 : RUN node_modules/.bin/ng build -aot --target ${TARGET} ---> Running in 09e5752964f6 Hash: 0c91b5245d9f2f1b899d Time: 12174ms chunk {0} polyfills.51d1b984c6d09b6245cd.bundle.js (polyfills) 232 kB {4} [initial] [rendered] chunk {1} main.466ececd219a11fbf397.bundle.js (main) 1.04 kB {3} [initial] [rendered] chunk {2} styles.4d1993091a9939c0785a.bundle.css (styles) 69 bytes {4} [initial] [rendered] chunk {3} vendor.927d5207264169ec1f8c.bundle.js (vendor) 836 kB [initial] [rendered] chunk {4} inline.e6088d403421d3b3ae62.bundle.js (inline) 0 … -
How do I create fields in another model using a migration?
I'd like to use contribute_to_class to extend the Group model in django by creating a migration pattern in my custom app. Is this possible using the migrations.AddField method? Here's a sample from the migration... migrations.AddField( model_name='contrib.auth.Group', name='created', field=django_extensions.db.fields.CreationDateTimeField(auto_now_add=True, default=django.utils.timezone.now, verbose_name='created'), preserve_default=False, ), Right now if I write the contribute_to_class code as follows it creates the migration in the django contrib.auth migrations folder which I'm trying to avoid for deployment reasons. Here's the code for the above... created = CreationDateTimeField(_('created')) created.contribute_to_class(Group, 'created')