Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: When passing a string with -,anything behind - get droped
I try to pass a string param on django,but when I try it,anything behind - get droped. I'm using Django 2.1.7 on Python3.My OS is Mac OS Mojave 10.14. I'm accessing http://127.0.0.1:8000/ruleset/a096abd9-3855-4a91-9336-1d7e66aa5323 def ruleSet(request,id_): return HttpResponse(id_) urlpatterns = [ path('admin/', admin.site.urls), re_path(r'ruleset/(\w+)', view.ruleSet) ] I except to get a096abd9-3855-4a91-9336-1d7e66aa5323 I got a096abd9 instead -
post content from json by Django
wanna build an easy RESTful demo as below: select song(show song id/song in html option) to show song information from json models.py class Music(models.Model): song = models.CharField(max_length=30) singer = models.CharField(max_length=30) music_pick.html {% extends 'main/base.html' %} {% block content %} <select id="music_select"> <option value="" selected="selected">---Song Select---</option> {% for m in musics %} <option value="option{{ m.id }}" selected="selected"> {{ m.song }} </option> {% endfor %} </select> <p>The song, {{ song }} was sang by {{ singer }}</p> {% endblock %} and I have done the json produce part as 'music/<^int:pk^>' it would return: { "id": 1, "song": "ICE AND FIRE", "singer": "George Martin", } how do I construct views.py or others in django 2.? -
AttributeError: module 'User.views' has no attribute 'User'
I created an app and assigned a path to url, created a function in 'views.py', and set up an app in 'setting.py'. Then I created a template folder in my app and created a file named home.html. However, you will still see the following error: AttributeError: module 'myapp.views' has no attribute 'home' -
need help to view PDF using Django
I'm new to Python & Django . I am trying to make a website for my personal project where you can upload & view pdf files but getting errors . Someone please help me to identify where i need to make corrections. This my models.py from django.db import models from datetime import datetime class PDF(models.Model): pdffile = models.FileField(upload_to='PDFs/') Title = models.CharField(max_length=500) Subject = models.CharField(max_length=500) created_at = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.Subject views.py from django.shortcuts import render from django.http import HttpResponse from .models import PDF def index(request): return HttpResponse("<h1>This is the Home Page</h1>") def pdf_view(request, PDF_id): a = PDF.objects.get(id=id) with open('a.pdf', 'rb') as pdf: response = HttpResponse(pdf.read(), contenttype='application/pdf') response['Content-Disposition'] = 'inline;filename=some_file.pdf' return response pdf.closed urls.py from django.shortcuts import render from django.http import HttpResponse from .models import PDF def index(request): return HttpResponse("<h1>This is the Home Page</h1>") def pdf_view(request, PDF_id): a = PDF.objects.get(id=id) with open('a.pdf', 'rb') as pdf: response = HttpResponse(pdf.read(), contenttype='application/pdf') response['Content-Disposition'] = 'inline;filename=some_file.pdf' return response pdf.closed -
customize help text per inline model instance in django admin
As per this answer: https://stackoverflow.com/a/50007209 it is possible to customize the help_text of a field in the admin depending on the current model object by overriding the get_form method in the ModelAdmin class, eg: def get_form(self, request, obj=None, **kwargs): if obj: help_texts = {'field_foo': get_some_string_based_on_obj(obj)} kwargs.update({'help_texts': help_texts}) return super(AuditPoliciesAdmin, self).get_form(request, obj, **kwargs) The key thing here is that the help text for field_foo can be computed based on the specific obj. I can't figure out how to achieve the same result for an InlineModelAdmin. The answer cited above mentions the need to override get_formset in a similar manner. However, the obj that is passed to get_formset is the parent model object, from which I don't know how to customize the help text of inlines. Consider that I have a House model with a tabular inline for Rooms. In the RoomAdmin, I can apply the help text customization as described above to present a room-specific text for field field_foo. Now, consider the HouseAdmin, which includes RoomInline. How can I apply the same customization of the help text of field field_foo for each of the related rooms? Of course, the customization should be specific to each Room instance, just as in the … -
How to make changes and take into effect to a deployed project
I deployed a Django/Python project using AWS. I am trying to make changes to a deployed project, but it won't take into effect even when I reboot the instance. What are the appropriate commands to make changes to a deployed project? I accessed the AWS server using the PEM key, and it showed that I'm on the server. I 'cd' into the project folder and use the following commands: "git add .--->git commit -a -m "message"--->git pull origin master. I see the changes took place in GitHub but as stated, even when I reboot the instance--the changes won't take place. Your feedback would be helpful! -
Change lookup regex in DRF Routers
How can we change the lookup regex for the lookup_field in a viewset and router? Conde Snippet # serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'is_staff') # views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = 'email' and if we try to access the detail-view as /api/v1/users/foo@bar.com/ it's raising a 404 -
How to make notifications when user open new tab or go to another tab?
I am working with project that include test,so when test started participators can't open other site or other tabs,and when they open new tab I want to show alert which will say that when is he sure to open new tab and finish my test I read about Window.focus and onbeforeunload ,but onbeforeunload works only when you are closing tab and focus didn't work properly Can you please help me ?I wrote whole project in django but i think i should use JS -
'say' is not recognized as an internal or external command
i am using windows 10. While doing my desktop assistant code using the Django framework of python, i face this problem after running my code. The assistant doesn't speak also. -
How to do an exclude django query on multiple foreign key
My model example: class Thing(models.Model): alpha = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='alpha_thing') beta = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='beta_thing') assigned_at = models.DateTimeField( _('assigned at'), null=True, help_text=_('Assigned at this date')) I wish to query all the users which don't have a Thing with an assigned_at date, ie they could have other Things, but that should have a date set. I've tried: return User.objects.exclude( alpha_thing__assigned_at__isnull=True ).exclude( beta_thing__assigned_at__isnull=True ).all() but the result is empty (the thing table is empty, so i'm not sure if it has something to do with the join?). -
I want to keep existing data about Imagefield in UpdateView
How can I maintain the contents of an ImageField when editing the data created by CreateView and form using UpdateView? I would like to delete or add to the data entered at the first time. In the case of CharField and TextField, they can be deleted and edited, so the same thing may not be possible. form.py class AppForm(forms.ModelForm): title = forms.CharField( widget=forms.TextInput, ) content = forms.CharField( widget=forms.Textarea, ) image = forms.ImageField( required=False, widget=forms.ClearableFileInput(attrs={'multiple': True}), ) -
Python Django POST request to different views
In Python Django, I sent a POST request to one view, called view1, and want to see that same POST request in another view, called view2. I tried to import that view1's method into view2, yet I just got that view1's method when doing a GET request to view2, not a POST request from view1 and seeing it in view2. view1.py @csrf_exempt def index(request): if "POST" == request.method: list_data = json.loads(request.body.decode('utf-8')) elif "GET" == request.method: list_data = serialize('json', ApiStatus.objects.all()) return HttpResponse(list_data, content_type='application/json') view2.py from app.views.view1 import index def status(request): print("STATUS request method ", request) # gives a GET request when reloading page print("INDEX method from view1.py ", index) # shows when doing GET request return render(request, 'template.html') post_file.py def get_test_req(): return { 'Samurai': 'Masamune'} def post_data(): data = [] data.append(get_test_req()) headers = {'Content-Type': 'application/json', 'Accept':'application/json'} r = requests.post(view1_url, headers=headers, json=data, timeout=10.0) Expected: To see post request from view1 into view2 after posting to view1. Actual: I only see a GET request in view2 and showing view1 as an imported value. -
chain query, needs to mock
python mocking the data with two filter is that possible def test_retrivelistService(self, param, most_recent_view_list): mock_MRVLists_data = mock.MagicMock(spec=mostRecentViewList) mock_MRV_data.userId = 6 mock_MRV_data.policyId= 6 mock_MRV_data.dbpolicyId = 6 mock_MRV_data.policyType = 6 mock_MRV_data.status = 6 mock_MRV_data.system = 6 mock_MRV_data.dateViewed = 6 most_recent_view_list.filter.return_value = [mock_MRVLists_data ] param.filter.exits.return_value = ">>>>True" def retrivelistService(userId): print("Exits",mostRecentViewList.objects.filter(userId=userId)[0].policyId) print("Exits",mostRecentViewList.objects.filter(userId=userId).exists()) if mostRecentViewList.objects.filter(userId=userId).exists(): mrdb = mostRecentViewList.objects.filter(userId=userId).order_by('dateview')[:5] mrvlist = [] for mrvs in mrdb: mrvDatas = {} mrvDatas["userId"] = mrvs.userId mrvDatas["policyId"] = mrvs.policyId mrvDatas["dbpolicytype'] = mrvs.dbpolicytype mrvDatas["status"] = mrvs.status mrvDatas["system"] = mrvs.system mrvLists.append(mrvDatas) else: mrvLists = [] return mrvLists this is the error im getting file "../../../.py" retrivelistService print("Exits",mostRecentViewList.objects.filter(userId=userId).exists()) AttributeError: 'list' object has no attribute 'exists' -
Django admin model relationship
So, I am building a Store website, I got 2 apps, one app called Store, it has two models "Store" and "UnitStore". The second app is called Product whereas it got single models called Store. In Product admin, I am using a formfield_for_foreignkey method to show StoreUnit and Store like this: "Store_name | Unit_name" So, my problem is that when I try to create a product, it always ask for a UnitStore's foreign key, but not all products comes from a UniStore, some product can only be found in a Store, therefore, I am not able to create a instance. - Models.py class Store(models.Model): store_name = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.store_name class UnitStore(models.Model): store_unit_name = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) store = models.ForeignKey( Store, related_name='units', on_delete=models.CASCADE, ) def __str__(self): return self.store_unit_name class Product(models.Model): product= models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) store_unit_name = models.ForeignKey( StoreUnit, related_name='units', on_delete=models.CASCADE, ) def __str__(self): return self.product - Product > Admin.py class CustomProduct(admin.ModelAdmin): model = Product list_display = ('product', 'created_at', 'aupdated_at', 'store_unit_name',) list_select_related = ('store_unit_name') fieldsets = ( ("Prodcut's Name:", { 'fields': ('product',)}), ('Store:', { 'fields': ('store_unit_name',)}), ) def save_model(self, request, obj, form, change): obj.created_by = request.user … -
Expiring URLs from S3 with django-summernote
I've recently started using django-summernote. It's any absolutely absolutely fantastic WYSIWYG editor. The images that I upload into summernote are written to my amazon S3 bucket. The problem is that the urls that represent these images expire after 1 hour. The result is that after 1 hour, rather than an image appearing on my site, I see a broken image link. I don't have this problem with any other media files uploaded to S3 via my site. I'm currently using boto 2.48.0. Do you you have any thoughts on why this might be and how I might be able to go about fixing this? Here is an example of one of the urls to an image that has expired: https://s3beanzoid.s3.us-east-2.amazonaws.com/media/django-summernote/2019-04-30/f0b21223-0f25-42c9-a206-4f02e95fb44e.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJZALJ3EN746L6QWQ%2F20190430%2Fus-east-2%2Fs3%2Faws4_request&X-Amz-Date=20190430T021533Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=b613ab77d8a0e339e66f7706e5b55ed2e413a969e747743865fe25156119f0ae Thanks for your time! -
How to return querysets and dictionarys
I'm trying to pass a queryset and a dictionary, context is the queryset, and for this example unassigned_samples2 the dictionary, in my template I can either get the dictionary to display or the queryset, but not both, it depends if I include the context queryset. Any ideas how to get this working? def detailcontainer(request, container_id): container = get_object_or_404(Container, pk=container_id) samples = container.samples.all() container_contents = container.samples.all() unassigned_samples = Sample.objects.all()[:10] unassigned_samples2 = Sample.objects.all() qs = Sample.objects.all() easting_query = request.GET.get('area_easting') northing_query = request.GET.get('area_northing') context_query = request.GET.get('context_number') sample_number_query = request.GET.get('sample_number') sample_type_query = request.GET.get('sample_type') if easting_query != '' and easting_query is not None: qs = qs.filter(area_easting__icontains=easting_query) if northing_query != '' and northing_query is not None: qs = qs.filter(area_northing__icontains=northing_query) if context_query != '' and context_query is not None: qs = qs.filter(context_number__icontains=context_query) if sample_number_query != '' and sample_number_query is not None: qs = qs.filter(sample_number__icontains=sample_number_query) if sample_type_query != '' and sample_type_query is not None: qs = qs.filter(sample_type__icontains=sample_type_query) qs = qs context = { 'queryset': qs } return render(request, 'container/detailcontainer.html', context, {'container':container, 'container_contents': container_contents, 'unassigned_samples': unassigned_samples, }) -
How to Model get a value from URL or etc
I have 2 Model with Foreign Key First model is "Reporter" Second model is "Article" My Article Add page url is : IP:8000/<Reporter-ID>/add_article/ My Article Model like that: class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) I want on my template, user can be select headline and pub_date , but reporter fill automaticly from URL or etc. How can I do this? I new on Django and my english level is low. I wish you understand me -
Django TemplateSyntaxError - 'staticfiles' is not a registered tag library
After upgrading to Django 3.0, I get the following TemplateSyntaxError: In template /Users/alasdair//myproject/myapp/templates/index.html, error at line 1 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz Here is my template {% load staticfiles %} <img src="{% static 'my_image.html' %}"> -
How to convert a django queryset to a dictionary for use as a template context
I'm recreating a precious stone inventory status report in Django which was originally built in Microsoft Access. The report is organized as follows: Deal ("ABC" - indicates house owned, consigned, partnership, etc.) Inventory Status (Inventory, Sold, Cost Only, Historical FYI, etc.) Detail lines (StoneID, Carats, Purchase Cost, etc.) Subtotals (Total Cost, Total Carats - being able to insert this in the correct place is where I'm stuck...) Here are the relevant parts of the models: class Deal(models.Model): deal_name = models.TextField() class Stone(models.Model): stoneid = models.TextField(verbose_name='StoneID', unique=True) dealid = models.ForeignKey(Deal, on_delete=models.PROTECT) ct_in = models.DecimalField(verbose_name='Carats', max_digits=7, decimal_places=3) cost_purchase = models.DecimalField(verbose_name='Purchase Cost', max_digits=14, decimal_places=2, null=True, blank=True) I get the data via two queries - one for the detail lines and the other for the subtotals. Here are the queries: def dump_stone(request): query = Stone.objects.filter(Q(dealid_id__deal_name='ABC') | \ Q(dealid_id__deal_name='DEF') | \ Q(dealid_id__deal_name='GHI')).select_related().order_by('dealid_id__deal_name', 'inventory_status', 'stoneid') totals = Stone.objects.values('dealid', 'inventory_status').annotate(sum_by_deal=Sum('cost_purchase'), sum_ct_in_by_deal=Sum('ct_in')) The template to print out the inventory detail tables by status, by deal is: {% block content %} REPORT: </br> {% regroup context by dealid as deal_list %} {% for dealid in deal_list %} {{dealid.grouper}} {% regroup dealid.list by inventory_status as stone_list%} {% for inventory_status in stone_list %} {{inventory_status.grouper}} <table> <thead> <tr> <th>StoneID</th> <th>Ct</th> <th>Cost</th> </tr> … -
How can an arbitrarily nested Django model (like a directory structure) be specified?
In my Django web app, I wish to create something like a directory structure using Django objects. In other words, the goal is to construct a Django model (say a model defined as Box) that can contain (or simply be associated with) an arbitrary number of other Box objects, along with an arbitrary number of Thing objects. What is the best way to accomplish this? Even better: is it possible to design the Box model to contain (or simply be associated with) even more objects, in addition to Thing, i.e. Gadget, Item, etc.? -
how to group different model updates when listening to post_save in changes
I have a bunch of models in my app for which I am listening to changes with post_save. Additionally I have an updated_at field on all of those which is a timestamp that will be updated on every save operation. Assuming a model Question with a one two many relationship with a model Answer the following happens: If I add an Answer then post_save will be triggered for both models (because of the timestamp update on Question). In my use case I need to know weather the Question itself was modified (in addition to updated_at) or if post_save was only triggered because an Answer was added. Is there a clean way to achieve this? -
Django throws existOperationalError for DB
Running Django throws 'conn = _connect(dsn, connection_factory=connection_factory, **kwasync) does not existOperationalError: FATAL: database "saleor"' I have used: CREATE USER saleor WITH PASSWORD 'somepassword'; CREATE DATABASE saleor WITH OWNER saleor ENCODING 'utf-8'; When i enter in terminal 'psql -U saleor' it works and logs in to db saleor with user saleor. My connection string is: 'postgres://saleor:somepassword@localhost/saleor' When i run 'python3 manage.py migrate' it throws an error as below: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/mnt/c/Users/Rick/projects/jorcustom/e-commerce/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/mnt/c/Users/Rick/projects/jorcustom/e-commerce/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/mnt/c/Users/Rick/projects/jorcustom/e-commerce/venv/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/mnt/c/Users/Rick/projects/jorcustom/e-commerce/venv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/mnt/c/Users/Rick/projects/jorcustom/e-commerce/venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/mnt/c/Users/Rick/projects/jorcustom/e-commerce/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 87, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/mnt/c/Users/Rick/projects/jorcustom/e-commerce/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/mnt/c/Users/Rick/projects/jorcustom/e-commerce/venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/mnt/c/Users/Rick/projects/jorcustom/e-commerce/venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/mnt/c/Users/Rick/projects/jorcustom/e-commerce/venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/mnt/c/Users/Rick/projects/jorcustom/e-commerce/venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/mnt/c/Users/Rick/projects/jorcustom/e-commerce/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/mnt/c/Users/Rick/projects/jorcustom/e-commerce/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/mnt/c/Users/Rick/projects/jorcustom/e-commerce/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/mnt/c/Users/Rick/projects/jorcustom/e-commerce/venv/lib/python3.6/site-packages/django/db/utils.py", line 89, … -
How to use a part of URL to filter models? (using tastypie)
Hello this is my first post. I have an api app using tastypie. It reads models from database. I would like to use a part of the api url to filter on certain objects. No arguments, just a part of url. For example, in an url : /api/cars/:registration/ I would like to filter for any car with this registration. I spent countless hours trying every option I have found on the web. It appears to me that the best option would be overriding get_object_list, but somehow I can't make it work. models.py class Cars(models.Model): car_registration = models.Int() signal_time = models.DateTimeField() pos_x = models.DecimalField(max_digits=9, decimal_places=6) pos_y = models.DecimalField(max_digits=9, decimal_places=6) urls.py cars_resource = CarsResource() urlpatterns = [ path('admin/', admin.site.urls), path('api/<int:registration>/', include(cars_resource.urls)), ] resources.py class CarsResource(ModelResource): def get_object_list(self, request): registration = self.kwargs['registration'] return super(CarsResource, self).get_object_list(request).filter(car_registration=registration) class Meta: queryset = Cars.objects.all() resource_name = 'cars' In result I usually get 404 error. I have a feeling that I am doing something wrong, but can't really find that place. -
How to evaluate the concatenation of 2 variables in a template?
I'm trying to evaluate the concatenation of 2 variable in my django template models.py class Product(models.Model): ProductId = models.AutoField(primary_key=True) ProductName = models.CharField(max_length=250) ProductBrand = models.CharField(max_length=250, blank=True, null=True) views.py def myfunction(request): headers = [] id_update = request.GET.get('id') product = Product.objects.get(ProductId=id_update) table = Product._meta.get_fields() for field in Product._meta.fields: headers.append(field.name) template = "courses/gototemplate.html" return render(request, template, {'headers': headers, 'product':product}) gototemplate.html {% extends "subfolder/base.html" %} {% block page-header %} {% endblock %} {% block content %} {% for header in headers %} <label for="name">{{ header }}</label> <input type="text" name="prod{{productId}}" value="{{ {{product}}.{{header}} }}"></br> </br> {% endfor %} The idea is to get the value of product for each product column table. -
How to make an array of Foreign Keys in Django - Postgresql
I'm trying to figure out how can I add an array of foreign keys in Django and Postgresql. Basically my goal is to be able to assign multiple category to any product. My Postgres table for the Category field looks like this: (Id, Name) (1, 'Adventure') (2, 'Family') And the Product table is structured like this: (Id, Title, Slug, Description, Image, Category_id) (95678, 'My Title', 'my-title', 'Lorem Ipsum ahgdg iahdid iahdia duaw', 'www.dummyimage.com/600x500/ffff', 1) Now I can't find a way to add multiple value (ids) inside of the Category_id field like this without getting an error: (Id, Title, Slug, Description, Image, Category_id) (95678, 'My Title', 'my-title', 'Lorem Ipsum ahgdg iahdid iahdia duaw', 'www.dummyimage.com/600x500/ffff', array[1, 2]) So how can I possibly solve this? I've tried replacing the ForeignKey field with an ArrayField and even with a ManytoManyField but still not working. My code looks like this currently: Models.py from django.db import models from django.urls.base import reverse class Category(models.Model): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name class Product(models.Model): title = models.CharField(max_length=255, default='') slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='') description = models.TextField(default='') image = models.ImageField(default='') category = models.ForeignKey(Category, related_name='category', default='', on_delete=models.SET_DEFAULT) def get_absolute_url(self): return reverse('product', kwargs={'slug': self.slug}) def __str__(self): return self.title …