Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid type for parameter Message
I try to use signal in django to send sns email in aws, my code is :- import boto3 from properties.models import PropertyList from django.db.models.signals import post_save, post_delete from django.dispatch import receiver @receiver(post_save, sender=PropertyList) def send_property_details(sender, instance, created, **kwargs): if created: sns = boto3.client('sns') response = sns.publish( TopicArn='arn:aws:sns:eu-west-1:238625232820:TestProperty', Message={ "default": instance.title }, MessageStructure='json', Subject='New Property Created', MessageAttributes={ 'default':{ 'DataType':'String', 'StringValue':instance.title } }, ) print(response['MessageId']) I get error as:- Invalid type for parameter Message, value: {'default': 'aws'}, type: , valid types: in AWS docs said If I want to send different messages for each transport protocol, set the value of the MessageStructure parameter to json and use a JSON object for the Message parameter. What is wrong in my code -
What settings are required for Heroku to communicate between Unity and the Django server in Heroku?
I want to communicate with a Django server deployed in Heroku using the UnityWebRequest class. The nodejs server our teammates have placed in Heroku works well, but the Django server I deploy does not. Of course, the Django server's connection to the Internet browser is nice, but strangely, Unity's request issued a Can not connect to Destination Host warning. I am using Heroku for free. Do I need a setting that I do not know on Heroku's dashboard? I do not want to use Socket for communication. Of course, communication via the WWW class was useless. Does anyone have experience with me? -
Django - Unable to display an image from folder within media folder
I am trying to load an image from a folder within 'media' folder (media/tshrirts) onto template using django. Below is my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_URL = '/media/' #MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_ROOT = 'media' **I tried both the roots none of them work. Below is my models.py from django.db import models # Create your models here. class tshirts(models.Model): brand=models.CharField(max_length=50) name=models.CharField(max_length=100) price=models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='tshirts/') def __str__(self): return self.name this is part of the tshirts.html <div class='tshirts'> {% for eachtshirt in alltshirts %} <div class='tshirt'> <a href="#">{{eachtshirt.brand}}</a> <p>{{eachtshirt.name}}</p> <p>{{eachtshirt.price}}</p> <img src="{{eachshirt.image.url}}"/> {% if eachshirt.image == None %} <p>{{"Image Not Found"}}</p> {% endif %} </div> {% endfor %} </div> finally, urls.py urlpatterns = [ . . . url(r'^tshirts/',include('tshirts.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) After I uploaded the image as an admin and clicked the link, the image was properly displayed. http://127.0.0.1:8000/media/tshirts/t-shirt2.jpg - the image was displayed here. How can I fix this, please let me know thanks!!! Screenshot for the page -
Python - Enable TLS1.2 on OSX
I have a virtualenv environment running python 3.5 Today, when I booted up my MacBook, I found myself unable to install python packages for my Django project. I get the following error: Could not fetch URL <package URL>: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:646) - skipping I gather that TLS 1.0 has been discontinued, but from what I understand, newer versions of Python should be using TLS1.2, correct? Even outside of my environment, running pip3 trips the same error. I've updated to the latest version of Sierra and have updated Xcode as well. Does anyone know how to resolve this? -
Django REST framwork mongoengine ValueError: The source SON object needs to be of type 'dict'
I'm working a project, and use Django REST framework and mongo engine, and I'm confused a question two days, and the detail see below: class Jvv(EmbeddedDocument): unit = fields.StringField() unitValue = fields.IntField() class Meta: db_table = 'imagerecognition' class ImageRecognition(Document): imageUrl = fields.StringField(default='', max_length=100) createTime = fields.DateTimeField(default=datetime.now()) ddPercent = fields.FloatField(required=False, default='') jvv = fields.ListField(fields.EmbeddedDocumentField(Jvv)) def __str__(self): return self.imageUrl class Meta: db_table = 'imagerecognition' then the serializer.p document is : class JvvSerializer(mongoserializers.EmbeddedDocumentSerializer): class Meta: model = Jvv fields = '__all__' class ImageUrlSerializer(mongoserializers.DocumentSerializer): jvv = JvvSerializer(many=True) class Meta: model = ImageRecognition fields = ('imageUrl', 'createTime', 'ddPercent', 'jvv') and the views.py content is below: class ImageUrlSave(views.APIView): def get(self, request, *args, **kwargs): imgs = ImageRecognition.objects(imageUrl='白菜') serializer = ImageUrlSerializer(imgs, many=True) ImageRecognition(imageUrl='土豆', ddPercent=8.22, jvv={'unit':'m', 'unitValue':12}).save() data = serializer.data return Response({ 'msg': 'SUCCESS', 'code_status': 1000, 'result': data }) the question is the mongodatabases have been completed, I want to take some data from it, but when I runserver, it shows raise ValueError("The source SON object needs to be of type 'dict'") ValueError: The source SON object needs to be of type 'dict', how can I handle this problem, and I am Looking forward to get answer. Thank you. -
Uploaded files/chunks are disappearing
I'm trying to set up a large file upload system using resumable.js and django. The front end is all properly configured, and for the django side of things I am using django-resumable. I'm using a very basic view to handle the upload: from resumable.views import ResumableUploadView from django.conf import settings from django.core.exceptions import ImproperlyConfigured class UserFileUploadView(ResumableUploadView): @property def chunks_dir(self): chunks_dir = getattr(settings, 'MEDIA_ROOT', None) if not chunks_dir: raise ImproperlyConfigured( 'You must set settings.MEDIA_ROOT') return chunks_dir When I upload a file, it appears to upload correctly, but I can't see the chunks or the completed file in the MEDIA_ROOT directory. If I cancel the upload, the server sometimes mentions a ConnectionAbortedError with a few AttributeErrors following it, and starting a new upload ignores all uploaded chunks. If I allow the upload to complete, I can't upload the file again until the page refreshes. In looking over the django-resumable code, I understand how it's supposed to function and can't see any reason why it shouldn't. Is there any way to figure out if the chunks are uploading, and where they're going if they are? -
django orm select from case when
i wanna to fetch some data from a subquery through django orm. here is my excepted sql SELECT "risk_level", COUNT("t"."id") FROM( SELECT "task_taskreport"."id" as "id", CASE WHEN MAX("task_vuln"."severity_points") >= 8.0 THEN 'high' WHEN (MAX("task_vuln"."severity_points") >= 5.0 AND MAX("task_vuln"."severity_points") <= 7.0) THEN 'middle' WHEN (MAX("task_vuln"."severity_points") >= 2.0 AND MAX("task_vuln"."severity_points") <= 4.0) THEN 'low' WHEN MAX("task_vuln"."severity_points") <= 1.0 THEN 'none' ELSE NULL END AS "risk_level" FROM "task_taskreport" LEFT OUTER JOIN "task_taskreport_vuln" ON ("task_taskreport"."id" = "task_taskreport_vuln"."task_report_id") LEFT OUTER JOIN "task_vuln" ON ("task_taskreport_vuln"."vuln_id" = "task_vuln"."vul_id") WHERE "task_taskreport"."subtask_id" = 21 GROUP BY "task_taskreport"."id" ORDER BY "task_taskreport"."id" DESC) as t group by "risk_level"; i have tried this TaskReport.objects.filter(subtask__pk=self.pk).\ annotate(max_points=Max('vulns__severity_points')).annotate( risk_level=Case( When(max_points__gte=8, then=Value('high')), When(max_points__gte=5, max_points__lte=7, then=Value('middle')), When(max_points__gte=2, max_points__lte=4, then=Value('low')), When(max_points__lte=1, then=Value('none')), output_field=models.CharField(), ) ).values('risk_level', 'pk').annotate(count=Count('risk_level')) but this throw a excepiton django.core.exceptions.FieldError: Cannot compute Count('risk_level'): 'risk_level' is an aggregate -
ERROR: test_board_topics_view_not_found_status_code (boards.tests.BoardTopicsTests), DoesNotExist: Board matching query does not exist
I am following the exercises at simpleisbetterthancomplex.com and I found the problem during TEST System check identified 1 issue (0 silenced). ...E............ ====================================================================== ERROR: test_board_topics_view_not_found_status_code (boards.tests.BoardTopicsTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/sysadmin/Documents/belajar_python/Django/mysite/boards/tests.py", line 41, in test_board_topics_view_not_found_status_code response = self.client.get(url) File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 536, in get **extra) File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 340, in get return self.generic('GET', path, secure=secure, **r) File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 416, in generic return self.request(**r) File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 501, in request six.reraise(*exc_info) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/sysadmin/Documents/belajar_python/Django/mysite/boards/views.py", line 13, in board_topics board = Board.objects.get(pk=pk) File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name DoesNotExist: Board matching query does not exist. ---------------------------------------------------------------------- is there anybody who can enlighten me? -
Django URL Redirects And Changing URL Structure
I'm trying to get some information before i change the URL structure of my website. I want to better organize the overall folder system for my 'deals website. currently my urls look like this for a specific deal : deals/discount-bike-at-walmart-99 for a specific category: deals/category/apparel for a specific retailer: deals/retailer-deals/walmart i feel like maybe these folders are a bit too long if i do want to change them, does django allready handle the redirects or is there something I need to do handle this? my site is allready indexed by google, so i'm trying to avoid an issue where I'm creating duplicated content -
django sessionid and csrrftoken and vue axios
I have a question about using vue axios frontend and Django backend in cors- domain environment. My cookie can use set-Cookie sessionid and csrftoken but frontend can't get these parameters to save to my document. If I use my chrome explorer, the application cookie is empty but I can find the cookie in response cookie header. But I won't use this csrftoken to backend verify in other POST AJAX, how can I resolve it to verify? I try a lot of settings, but not work in using @csrf_protect function, though just remove it and use @csrf_emept can work. How can I keep csrftoken work in this situation? Thanks. The followings are what I use settings. axios settings axios.defaults.headers.get['Accept'] = 'application/json' axios.defaults.headers.post['Content-Type'] = 'application/json' axios.defaults.withCredentials = true Django settings MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.gzip.GZipMiddleware', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-CSRFToken', 'X-CSRFToken', 'csrftoken', 'x-requested-with', ) CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True -
Post method cannot pass to view function
I fill in the form but get an empty result. The new_entry page: The page it redirect(which intend to return the new entry. The new_entry function in views.py def new_entry(request, topic_id): """Add a new entry for a particular topic.""" topic = Topic.objects.get(id=topic_id) if request.method != 'POST': #No data submitted, create a blank form. form = EntryForm() print("get") # test point else: # POST data submittd; process data form = EntryForm(data=request.POST) print('Post') # test point # print('request: ', request) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id])) context = {'topic':topic, 'form':form} return render(request, 'learning_logs/new_entry.html', context ) It print 'get' on the console Quit the server with CONTROL-C. get [11/May/2018 01:40:16] "GET /new_entry/3 HTTP/1.1" 200 452 Request method is "POST" in "new_entry.html" {% block content %} <p> <a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a> </p> <p>Add a new entry:</p> <form action="{% url "learning_logs:topic" topic.id %}" method="POST"> {% csrf_token %} {{ form.as_p }} <button name="button">add entry</button> </form> {% endblock content %} The form.py was doublechecked class EntryForm(forms.ModelForm): class Meta: model = Entry fields = ['text'] labels = {'text':''} widgets = {'text':forms.Textarea(attrs={'cols':80})} What's the problem with my code? -
Django - Get Value Only from queryset
When the docs discuss values() and values_list(), or any query for that matter, they always require that you know what you are looking for, i.e., >>> Entry.objects.values_list('headline', flat=True).get(pk=1) 'First entry' What about the situation where you need a value from a specific field, whether on this model or a foreign key, but you don't know the pk or the value in the specified field, and you don't care, you just need whatever is there. How do you query for it? Alternatively, if I use this example from the docs: >>> Entry.objects.values_list('id', flat=True).order_by('id') <QuerySet [1, 2, 3, ...]> Could I add slice notation to the end of the query? But even then, I might not know in advance which slice I need. In other words, how to dynamically get a value from a specified field without knowing in advance what it or its pk is? Thx. -
How Can I Display Users Posts also whether it is logged in or logged out
I want to Display Users Posts also whether it is logged in or logged out When I click the everyone User It will show me users Profile Info but I want everyone user's posts also How Can I Solve This?? Here is my code https://dpaste.de/KBcF Thank You in Advance -
Django Sitemaps Not Showing My Blogposts
I'm using the Django Sitemap Framework. You can see my sitemap here: https://dealmazing.com/sitemap.xml It seems to be picking up my blog at /blog but not my actual blog posts. it looks like it is recording the actual posts over and over again as dealmazing.com/blog but without the real URL This is my sitemaps.xml file from django.contrib import sitemaps from django.contrib.sitemaps import Sitemap from django.urls import reverse from deals.models import Deal, Category, Retailer from blog.models import Post, BlogCategory class StaticViewSitemap(sitemaps.Sitemap): priority = 1.0 changefreq = 'daily' def items(self): return ['about', 'contact', 'disclosure', 'terms', 'privacy', 'deals:deals', 'blog:blog'] def location(self,item): return reverse(item) class BlogSitemap(Sitemap): changfreq = "daily" priority = 1.0 location ='/blog' def items(self): return Post.objects.filter(status='Published') def lastmod(self, obj): return obj.created class BlogCategorySitemap(Sitemap): changfreq = "daily" priority = 1.0 def items(self): return BlogCategory.objects.all() class DealCategorySitemap(Sitemap): changfreq = "daily" priority = 1.0 def items(self): return Category.objects.all() class RetailerSitemap(Sitemap): changfreq = "daily" priority = 1.0 def items(self): return Retailer.objects.all() class DealSitemap(Sitemap): changfreq = "daily" priority = 1.0 def items(self): return Deal.objects.all() def lastmod(self, obj): return obj.date_added and in my urls file sitemaps = { 'static': StaticViewSitemap, 'blog': BlogSitemap, 'blog-category': BlogCategorySitemap, 'deals': DealSitemap, 'deals-category': DealCategorySitemap, 'retailers': RetailerSitemap } path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), I can't quite … -
Django Forms: If I use charfield in form, do I need to use clean_field?
In my forms, if I have the following class with a field for my charfield 'bio' class MyClass(forms.ModelForm): bio = forms.CharField(max_length=1000 Do I need to have the below validation or does the above max_length=1000 already cover that? def clean_bio(self): bio=self.cleaned_data['bio'] max_length = 1000 if len(bio) > max_length: raise forms.ValidationError('Please limit your bio to 1000 words') return bio -
Can not install "wfastcgi 2.1 gateway for iis and python 2.7.9" in IIS
I have a error installing "wfastcgi 2.1 gateway for iis and python 2.7.9" in IIS, to deploy an app django in windows 10. I can not download the installer (see the image). enter image description here Please, have someone the installer? Thanks in advance! -
Django: How to get parent url when iframe is loaded
I am using @xframe_options_exempt in my django view so that I can load this view from an iframe. I want to do some if url = xxx filtering on the page but I need to get the Parent URL of the iframe. For example the parent url is "http://mycoolsite.com" which loads "http://mycooldata.com/data" in an iframe. If i do something like request.get_absolute_uri, it will return "http://mycooldata.com/data" (the url that the iframe is) when i want it to return parent url of "http://mycoolsite.com" instead. Any ideas on how to get that to happen? Using python 3.6 and django 1.11. Thanks, jAC -
Django ValidationError formating in a For Loop
I've written a series of RegexValidator definitions that I call on django model inputs. Here is an example: def fein_validator(value): err = None for validator in FEIN_VALIDATOR: try: validator(value) return value except ValidationError as exc: err = exc raise err For reference the FEIN_VALIDATOR for this method is below. Note that in this example there is only a single item, I have other validators that have multiple items (hence the for loop): FEIN_VALIDATOR = [ RegexValidator(r'^\d{2}-\d{7}$') ] The method works perfectly and throws an error when it's supposed to. But, the error it throws is Enter a valid value. and I would like to customize the return to be more specific. I've tried versions of this and this. But these all assume that there is only one pass. I'm trying to run through a series of validators using a for loop. Question 1: does the method construction I'm using work for this - or should there be a separate method for each validation? [whereby I can add custom messaging.] Question 2: if this does work, how do I change the error message raised to a custom message? -
Catch Permission Denied TestCase django
Currently I'm testing out a decorator user_is_property_author as seen here. the self.user2.id works fine as well self.property.unique_id the only problem is that my output. cannot be grab from the test. def user_is_property_author(function): def wrap(request, *args, **kwargs): if 'user_session' in request.session: try: unique_id = kwargs['unique_id'] user_session = request.session['user_session'] if not unique_id: raise ValueError('unique_id missing') if not user_session: raise ValueError('user_session is missing') entry = Property.objects.get(unique_id=unique_id) if entry.user.id == user_session: return function(request, *args, **kwargs) else: raise PermissionDenied except Property.DoesNotExist: raise PermissionDenied raise PermissionDenied wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap And here is my test def test_user_is_property_author_fail(self): request = self.factory.get(reverse(edit_property, kwargs={'unique_id': self.property.unique_id})) request.session = {'user_session': self.user2.id} response = edit_property(request, unique_id=self.property.unique_id) self.assertRaises(PermissionDenied, response) my test error stack trace ====================================================================== ERROR: test_user_is_property_author_fail (properties.test.test_decorators.TestUserModel) Traceback (most recent call last): File "/rentyapp/properties/test/test_decorators.py", line 73, in test_user_is_property_author_fail response = edit_property(request, unique_id=self.property.unique_id) File "/rentyapp/users/decorators.py", line 10, in wrap return function(request, *args, **kwargs) File "/rentyapp/properties/decorators.py", line 24, in wrap raise PermissionDenied django.core.exceptions.PermissionDenied Ran 31 tests in 6.101s FAILED (errors=1) -
Get list of all rooms (Django channels 2)
Is it possible to get list of all created rooms in Django channels 2.x? I have checked documentation and there is no method which returns list of created rooms. -
Batch requests Gmail API
I have a python project (Django) connected to Gmail API. I need to get all the messages that the user has and save 'metadata' of every message. If I do that with a loop and make one request for message[i] - this will be slow. Well, now I have this spaghetti code with these while loops. (What I do else is I store "From" and "To" addresses from metadata of every message and count who sent you messages the most). This code is slow and hard-readable, probably because of those one-by-one requests: import operator from googleapiclient import errors from .quickstart import service def getTop(n): try: label = '' if n == 1: label_ids = "INBOX" label = "From" else: label_ids = "SENT" label = "To" user_id = "me" topers = service.users().labels().get(userId=user_id, id=label_ids).execute() count = topers['messagesTotal'] topers = service.users().messages().list(userId=user_id, labelIds=label_ids).execute() tmp = [] st = [] if 'messages' in topers: tmp.extend(topers['messages']) l = len(tmp) for i in range(0, l): idshka = tmp[i]['id'] mdata = service.users().messages().get(id=idshka, userId=user_id, format='metadata', metadataHeaders=[label]).execute() head = mdata['payload']['headers'] obval = head[0]['value'] # algo/////////////////////// t = str(obval) t = t.split('<', 1)[-1] t = t.replace('>', "") st.append(t) while 'nextPageToken' in topers: tmp = [] page_token = topers['nextPageToken'] length = len(page_token) … -
How to include most recent entry from a reverse FK when exporting from django admin to csv files?
I have the following models: class Person(models.Model): name = models.CharField(max_length=45) etc... class Clothes(models.Model): person = models.ForeignKey(Person) etc... I have the following in admin.py class ExportCsvMixin: def export_as_csv(self, request, queryset): meta = self.model._meta field_names = [field.name for field in meta.fields] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta) writer = csv.writer(response) writer.writerow(field_names) for obj in queryset: row = writer.writerow([getattr(obj, field) for field in field_names]) return response export_as_csv.short_description = "Export Selected as CSV" class PersonAdmin(admin.ModelAdmin, ExportCsvMixin): actions = ["export_as_csv"] etc... This works great and I can export a csv file with all the fields from Person. How would I go about including the most recent record of the Clothes model as a field to the csv export? -
ThreadPoolExecutor fails when run with manage.py
# test.py # python 3.4.5 import time from concurrent.futures import ThreadPoolExecutor def a(): time.sleep(1) print("success") executor = ThreadPoolExecutor(1) executor.submit(a).result() The above snippet works when run like $ python test.py success But fails when run like $ python manage.py shell < test.py Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/core/management/commands/shell.py", line 101, in handle exec(sys.stdin.read()) File "<string>", line 11, in <module> File "/usr/lib64/python3.4/concurrent/futures/_base.py", line 395, in result return self.__get_result() File "/usr/lib64/python3.4/concurrent/futures/_base.py", line 354, in __get_result raise self._exception File "/usr/lib64/python3.4/concurrent/futures/thread.py", line 54, in run result = self.fn(*self.args, **self.kwargs) File "<string>", line 7, in a NameError: name 'time' is not defined Which is really strange to me. What is it about running the script with the manage.py shell command that results in the time module being undefined in the function a? -
Get non-deleted forms from Django formset
When I use a formset that's both can_order and can_delete I'm able to get all the deleted forms with .deleted_forms and all the non-deleted forms (in order) with .ordered_forms. If I use a formset that doesn't use can_order I no longer have access to .ordered_forms (it throws an exception). Is there an easy way to get the list of forms that are not deleted? The closest I can find is manually creating it with: [form for form in formset.forms if not formset._should_delete_form(form)] However, that's using a "hidden" method and it seems odd there's not something already built-in. -
(Django) DetailView template not displaying information
within my maintenance app I have six models. I will include only 2 of the models that is relevant towards this question. There is a list of equipment(Listview) which displays properly. However, I'm having problem creating a detailview for each equipment. When i go to the url 'http://127.0.0.1:8000/maintenance/equipments/1' it should display all equipment instance(details) relevant to equipment 1 but it displays back the equipment list page, i.e, http://127.0.0.1:8000/maintenance/equipments/'. **MODEL** from django.db import models class Equipment(models.Model): """ Model representing an Equipment (but not a specific type of equipment). """ title = models.CharField(max_length=200) physicist = models.ForeignKey('Physicist', null=True, help_text= 'add information about the physicist') technician = models.ForeignKey('Technician', null=True, help_text= 'add information about the technician') # Physicist as a string rather than object because it hasn't been declared yet in the file. features = models.TextField(max_length=1000, help_text='Enter a brief description of the features of the equipment') machine_number = models.CharField('Number', max_length=30, null=True, help_text='Enter the Equipment number') specialty = models.ForeignKey(Specialty, null=True, help_text='Select a specialty for an equipment') # Specialty class has already been defined so we can specify the object above. assigned_technician = models.CharField(max_length=50, null= True, blank=True) #This is for the Technician who the repair of the Equipment is assigned to. def __str__(self): return self.title def get_absolute_url(self): …