Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
os.system(inpsectdb) runtime doesn't not create model
To my problem: I need to create a model during runtime. We create new database and fill them with tables and information. After that we need to create the model for the database. I do that with the following code: os.system("python3 D:/django/alpha/manage_inspectdb.py inspectdb --database realtest > D:/django/alpha/api_manager/schemas/realtest.py") When I run the command in program I get an empty realtest.py file. When I run the command on command line I get the expected result a realtest.py with all the generated classes. I found out that this does work when i run it on my local Computer. As soon as i try to push it in deployment i doesnt work anymore. In deployment i have Apache Server with Python and Django all up-to-date. -
How to hide a button if the user don't have permission?
I'm working as an intern for a company on GeoNode 2.8. I have to hide the Download Layer button if the user is not in the permission list. The previous intern made it in an older version of Geonode by adding a {% get_obj_perms request.user for resource.layer as "perms" %} before the button display function. But when I add it on my version of GeoNode, it didn't change anything and the button still there. {% if resource.storeType != "remoteStore" %} {% get_obj_perms request.user for resource.layer as "layer_perms" %} <li class="list-group-item"> {% if links or links_download %} <button class="btn btn-primary btn-md btn-block" data-toggle="modal" data-target="#download-layer">{% trans "Download Layer" %}</button> {% else %} {% if request.user.is_authenticated %} <button class="btn btn-primary btn-md btn-block" id="request-download">{% trans "Request Download" %}</button> {% endif %} {% endif %} </li> {% endif %} -
What is The Standard Way to Structure Django Rest urls
I have a project in which I have several app: project/app1 project/app2 In those apps exist views for which I want to have basic CRUD. So the usual way for the urls is to use routers. app1/api/views: class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer So far so good. I register a router under this path: project/urls.py But, if I want to add other views under app1, I don't know how to structure the urls. Let's say I want to list reviews about a specific book: class TestAssesment(ListCreateAPIView): def get_queryset(self): queryset = BookReviews.objects.filter( book_id=self.kwargs["pk"]) return queryset serializer_class = BookReviewSerializer The url I'm seeking is: books/<int:id>/reviews/ Where and how should I put this url? Shoud I dismiss the router inside project/urls.py and replace it with path('books/', include('books.api.urls')) and handle all the related urls there? What is the cleanest way to structure URLs in such cases? -
How to style django-allauth Template?
I'm new in Django, so i don't know how to give style to my templates. I had read the Allauth official Docs but i don't understand how to style them? i had downloaded the templates from github and did all the dir settings. and now its working. this is my login template which i have to convert into django allauth template. <div class="container"> <div class="col-sm-10 main-section ml-auto mr-auto"> <div class="card text-center shadow p-0 mb-0"> <div class="card-header"> <ul class=" nav nav-tabs card-header-tabs"> <li class="nav-item ml-auto"> <button type="button" class="close nav-link" aria-label="Close" > <span aria-hidden="true"><a href="index.html">&times;</a></span> </button> </li> </ul> </div> <div class="card-body"> <div class="modal-content"> <form class="col-sm-11 ml-auto mr-auto"> <h1 class="heading ">Login </h1> <div class="form-group"> <input type="email" class="form-control" placeholder="Enter Email"> </div> <div class="form-group"> <input type="password" class="form-control" placeholder="Password"> </div> <button type="submit" class=" btn col-sm-6 ml-auto mr-auto" id="log- icon">Login</button> <div class="col-sm-6 forgot ml-auto mr-auto"> <a href="#">Forgot Password?</a> </div> <div class="col-sm-6 forgot ml-auto mr-auto"> <a href="signup_E.html">Create an Account</a> </div> </form> </div> </div> </div> </div> </div> And the Allauth template look like this , i'm uploading only the direct login form of allauth <p>{% blocktrans %}If you have not created an account yet, then please <a href="{{ signup_url }}">sign up</a> first.{% endblocktrans %}</p> {% endif %} <form class="logi`enter … -
Create input field in django ModelForm through autocomplete select
I have a dynamic DropDownBox in Django ModelForm through autocomplete select2. Selections are coming out properly, but I don't know how to save new choices into the database through autocomplete select2. Help me to solve. My ModelForm Title = forms.ModelChoiceField(queryset=Book1.objects.values_list('Title', flat=True).distinct(), widget=autocomplete.ModelSelect2()) class Meta: model = Book1 fields = [ 'Title'] class Book1Admin(admin.ModelAdmin): form = Book1Form save_as = True -
My images are stored in the Django model but not in my media directory unless if the page gets refreshed. How to solve this issue?
I've created a simple image upload page which allows a user to upload an image from the system. It rejects any extensions other than PNG, JPEG, JPG and SVG. Once successful, the user will get sent to a page which states that the image upload is successful. However, once returned back to the image upload page; when a user uploads again without refreshing the page, the image gets stored into the Django model but not in the media directory. What's the reason for this? I'm using Django 2.2.2 version and am currently new to it. Code: models.py from django.db import models import os from PIL import Image from datetime import date import datetime from .validators import validate_file_extension import base64 def get_directory_path(instance, filename): today = date.today() t = datetime.datetime.now() day, month, year = today.day, today.month, today.year hour, minutes, seconds = t.hour, t.minute, t.second filename = str(day) + str(month) + str(year) + str(hour) + str(minutes) + str(seconds) + '.png' dir = 'media' path = '{0}/{1}'.format(dir, filename) return path class Image(models.Model): image = models.FileField(upload_to = get_directory_path, default = 'media/sample.png', validators=[validate_file_extension]) created_date = models.DateTimeField(auto_now = True) def __str__(self): return str(self.id) @property def image_url(self): with open(self.image.path, "rb") as imageFile: base64.b64encode(imageFile.read()) with open(self.image.path, "wb") as fh: … -
how to set callback and website url for localhost in twitter app
i am getting this problem and how should i add best call back url in twitter app Website URL http://localhost:8000/ http://127.0.0.1:8000/ http://twitter/username/ http://example.com callback url http://localhost:8000/ https://localhost:8000/ http://127.0.0.1:8000/ http://localhost:8000/auth/twitter/callback/ http://twitterusername.com/ http://127.0.0.1/complete/twitter/ http://127.0.0.1/oauth/complete/twitter/ http://127.0.0.1/folder_name/ HTTPError at /social-auth/login/twitter/ 403 Client Error: Forbidden for url: https://api.twitter.com/oauth/request_token -
Django group by only using users_id and get all other fields from model
views.py condition = Q(vendor_id=vendor_id) sum_invoice_qry = Sum('amount', filter=Q(transaction_type=1)) sum_payment_qry = Sum('amount', filter=Q(transaction_type=2)) qs = Transaction.objects.values('users_id').annotate(sum_invoice=sum_invoice_qry).annotate(sum_payment=sum_payment_qry).filter(condition) => I need to group by users_id and all other fields from model, - But, currently it is making this query: SELECT `tbl_transactions`.`users_id`, SUM(CASE WHEN `tbl_transactions`.`transaction_type` = 1 THEN `tbl_transactions`.`amount` ELSE NULL END) AS `sum_invoice`, SUM(CASE WHEN `tbl_transactions`.`transaction_type` = 2 THEN `tbl_transactions`.`amount` ELSE NULL END) AS `sum_payment` FROM `tbl_transactions` WHERE (`tbl_transactions`.`vendor_id` = 3544 AND `tbl_transactions`.`billing_type` = ) GROUP BY `tbl_transactions`.`users_id`, `tbl_transactions`.`date_time`, `tbl_transactions`.`date_added` ORDER BY `tbl_transactions`.`date_time` DESC, `tbl_transactions`.`date_added` DESC => Why the date_time and date_added is appended in group by? how to remove them => How to get all others fields, like vendor_id, amount... from models models.py from django.contrib.auth import get_user_model from django.db import models # Create your models here. class Transaction(models.Model): users = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) vendor_id = models.IntegerField(blank=True) transaction_id = models.CharField(max_length=100,blank=True) #transaction_type = models.CharField(max_length=100,blank=True) TYPE_CHOICES = ((0, 'Select Transaction Type'),(1, 'Invoice'), (2, 'Payment')) transaction_type = models.IntegerField(default=0,blank=True,choices=TYPE_CHOICES) amount = models.DecimalField(max_digits=15,decimal_places=2) out_std_amount = models.DecimalField(max_digits=15,decimal_places=2,blank=True) description = models.TextField(blank=True) attachment = models.ImageField(upload_to="images/transactions/%Y/%m/%d",blank=True) quantity = models.IntegerField(default=0) billing_type = models.CharField(max_length=50,blank=True) date_time = models.DateTimeField(auto_now=False) added_by = models.IntegerField(blank=True) date_added = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): super(Transaction, self).save(*args, **kwargs) class Meta: db_table = 'tbl_transactions' ordering = ['-date_time','-date_added'] def __unicode__(self): return self.transaction_id -
MySQL (1118, 'Row size too large (> 8126)) & increasing innodb_log_buffer gives me error
I'm running a staging server on an Ubuntu 16.04, When I try to save a particular document, I get the following error: OperationalError at /product/1172 (1118, 'Row size too large (> 8126). Changing some columns to TEXT or BLOB or using ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED may help. In current row format, BLOB prefix of 768 bytes is stored inline.') The document contains many text fields with anywhere between 10 - 1000 characters. When I delete some of the text, I could actually save the document just fine. So it's probably character bound. The interesting bit is that when I try to clone the same document details into my local MYSQL version, it works just fine. So my next logical step was to compare innodb_ global variabls. I compared and the only variable that was different was innodb_log_buffer_size was set to 16M on local, but 8M on the staging version. So I tried to set it up from mysql.conf under [mysqld] statement. However, when I try to restart the service for mysql, I get the following error: Job for mysql.service failed because the control process exited with error code. See "systemctl status mysql.service" and "journalctl -xe" for details. And when checking the … -
Success-message not working in Django Class based Createview
I have my View Below I tried everything but Success-message not working in Django Class-based Createview. Where I am wrong? class TaskCraeteView(LoginRequiredMixin,CreateView): model=Task success_message = "Task Craeted successfully!" reverse_lazy('create-task') login_url = 'login' template_name = 'create-task' form_class = TaskCreateForm get_success_url ="/" def form_valid(self,form): print(form.cleaned_data) form.instance.task_assign_by = self.request.user server = form.save(False) server.save() # form.save() task= Task.objects.latest('id') print(type(task)) for users in form.cleaned_data['task_assign_to']: TaskComplete.objects.create(completed_by=users, task_id= task) for p in form.cleaned_data['task_perticulars']: task.task_perticulars.add(p) for t in form.cleaned_data['task_subtask_name']: task.task_subtask_name.add(t) return HttpResponseRedirect("add") -
How to make dropdown menu to be visible when hover in django?
I have made a dropdown menu in django so that a user could select one option but whenever I click on dropdown menu, all the contents hide itself except the one I hover a mouse on it. How to make all the contents visible?? forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image','payment_method','detail'] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) payment_method = models.CharField(max_length=10, choices=Paymet_choices) profile.html {{p_form|crispy}} -
Django rest framework where to write complex logic in serializer.py or views.py?
I am new to Django Rest Framework. Using serializer and views a simple CRUD is easy. When the logics increase, it is quite confusing where to write logics in serializer or views. Some developers do prefer "Thick serializer and thin views" and some developers "Thick views and thin serializer". Maybe this is not a big issue and I think it is up to the developer whether to write more on views or serializer, but as a newbie what will be your suggestion to follow? Should I write more on views or serializer? There are many answers on Django View Template but can not find a satisfying answer for Django Rest Framework. Thoughts of experienced developers will be highly appreciated. Thank you. -
how to poll message from SQS using celery worker, the message is in JSON format and worker not able to decode the format
how to poll message from SQS using celery worker, the message is in JSON format and worker not able to decode the format Note: These messages are not sent into SQS using celery beat, This queue is subscribed from SNS my celery worker command is: celery worker -A status_handling -l info -Q es_status_test Msg in Queue: { "Type" : "Notification", "MessageId" : "f7e40fd9-8f92-59c5-afd9-5a1847aaae57", "TopicArn" : "arn:aws:sns:us-west-2:410317669909:email_service_responses-testing", "Message" : "{\"SESResponseStatusCode\": 200, \"Status\": \"Delivered\", \"Message\": \"Email sent successfully.\", \"MessageId\": \"a59e85a2-8b7a-4b49-9354-0a7a4170b0c0\", \"Uuid\": null}", "Timestamp" : "2019-08-05T06:00:24.943Z", "SignatureVersion" : "1", "Signature" : "Ofa0Xh20WfBha1sXOdqcs967/4m4/2398cm47hmFB/Tk8i47thL5ge6X6hCO/SuL1fE7yC0/2vVaC2s22HOlAwtnpPmOVWwno3h3OQq8B/lqdbKBriYan0U10ye0WtPPfjkPsRJyfDwit1QKf80vmUXjt9ccqGIBm+fJwS8zeLnn/Z8KWqOhr+VQBzK+cNZOotdhxE0M8Paah8/C3gqaBHc3Yi89dV2dZUF56mexMK+mccNo9ScGVTJrbfWHkKK/cQeD0pgUpfPKPsmGAyQzaBKAe9Nx24lqsGFSE8GGItVWdv9x9xCh8/q+HimRAP0pM24FcqqczVGu+CXe/lZcnQ==", "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-6aad65c2f9911b05cd53efda11f913f9.pem", "UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:410317669909:email_service_responses-testing:e493364b-b593-4134-8c0e-c60fc8feebe8" } Error is coming: [2019-08-04 23:00:25,116: CRITICAL/MainProcess] Unrecoverable error: JSONDecodeError('Expecting value: line 1 column 1 (char 0)') Traceback (most recent call last): File "/home/vagrant/env/lib/python3.7/site-packages/celery/worker/worker.py", line 205, in start self.blueprint.start(self) File "/home/vagrant/env/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/home/vagrant/env/lib/python3.7/site-packages/celery/bootsteps.py", line 369, in start return self.obj.start() File "/home/vagrant/env/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 318, in start blueprint.start(self) File "/home/vagrant/env/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/home/vagrant/env/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 596, in start c.loop(*c.loop_args()) File "/home/vagrant/env/lib/python3.7/site-packages/celery/worker/loops.py", line 91, in asynloop next(loop) File "/home/vagrant/env/lib/python3.7/site-packages/kombu/asynchronous/hub.py", line 362, in create_loop cb(*cbargs) File "/home/vagrant/env/lib/python3.7/site-packages/kombu/asynchronous/http/curl.py", line 111, in on_readable return self._on_event(fd, _pycurl.CSELECT_IN) File "/home/vagrant/env/lib/python3.7/site-packages/kombu/asynchronous/http/curl.py", line 124, in _on_event self._process_pending_requests() File "/home/vagrant/env/lib/python3.7/site-packages/kombu/asynchronous/http/curl.py", line 130, in _process_pending_requests self._process(curl) File "/home/vagrant/env/lib/python3.7/site-packages/kombu/asynchronous/http/curl.py", line … -
access post phone numer&message chat enable or disable?
we have 3plans Basic , Premium and pro..... type of users registerd/subscribe with plan. whe hve problem is Basic posted image with access to premium, so premium customer can access full details of phone/chat are enable and he can see.but pro customer can see only details but he can't see phone/chat because he don't have access? please tell me how to write code for this in python django? id,plan:1 Basic ,2 Premium,3 pro if request.method == "POST": if 'userblogpostview' in request.POST: posview_results = AddNewposts.objects.get(id=id) postimg_results=Useruploadedpostimages.objects.filter(newpost_id=posview_results.id).all() subcriptionname = Userinformation_tbl.objects.get(userinfo_id=request.user.id) if user.is_active: subcriptionname = Userinformation_tbl.objects.get(userinfo_id=request.user.id) return render(request, 'widgetsapp/userpostblogview.html',{'i1': posview_results, 'postimg_results': postimg_results,'subname':subcriptionname}) else: subname='XXXXXXXXX' return render(request, 'widgetsapp/userpostblogview.html', {'i1': posview_results, 'postimg_results': postimg_results, 'subname': subcriptionname}) return render(request, 'widgetsapp/userpostblogview.html',{'i1': posview_results, 'postimg_results': postimg_results,}) when we are login only it works , if not login it showing error? -
Django Warning (urls.W005) URL namespace isn't unique urls
Hi I'm getting this error when doing my migrations or using the python manage.py runserver command. WARNINGS: ?: (urls.W005) URL namespace 'suppliers' isn't unique. You may not be able to reverse all URLs in this namespace ?: (urls.W005) URL namespace 'teachers' isn't unique. You may not be able to reverse all URLs in this namespace This is my urls.py inside my app directory (classroom): from rest_framework_simplejwt.views import TokenRefreshView from classroom.views.classroom import * from .views import classroom, suppliers, teachers urlpatterns = [path('', classroom.home, name='home'), path('sign-in/', SignInView.as_view(), name='get-token'), path('refresh/', TokenRefreshView.as_view(), name='refresh-token'), path('username/available/', is_username_available, name='username-available'), path('sign-up/', CreateUserView.as_view(), name='sign-up'), path('current_user/', current_user), path('users/', UserList.as_view()), path('createrfq/', createrfq.as_view()), path('suppliers/', include(([path('load', suppliers.QuizListView.as_view(), name='quiz_list'), path('interests/', suppliers.SupplierTruckView.as_view(), name='supplier_trucks'), path('home/', suppliers.TakenQuizListView.as_view(), name='taken_quiz_list'), path('quiz/<int:pk>/', suppliers.take_quiz, name='take_quiz'), path('quiz/edit/<int:pk>/', suppliers.edit_quiz, name='edit_quiz'), # teachers modules path('quiz/add/', suppliers.QuizCreateView.as_view(), name='quiz_add'), path('quiz/confirm/<int:pk>/', suppliers.QuizUpdateView.as_view(), name='quiz_change'), path('quiz/<int:pk>/delete/', suppliers.QuizDeleteView.as_view(), name='quiz_delete'), path('quiz/<int:pk>/question/add/', suppliers.question_add, name='question_add'), path('quiz/<int:quiz_pk>/question/<int:question_pk>/', suppliers.question_change, name='question_change'), path('myposts/', suppliers.QuizListView1.as_view(), name='quiz_change_list'), path('myposts/<int:pk>/results/', suppliers.QuizResultsView.as_view(), name='quiz_results'), path('upload/pod/<int:pk>', suppliers.pod_upload, name='model_form_upload'), # path('pod/', suppliers.image_path, name='pod'), path('financials/', suppliers.invoices, name='financials'), path('lr/<int:pk>/', suppliers.LrFormView, name='lr_form'), path('printlr/<int:pk>/', suppliers.PrintLR, name='lr_print'), path('invoice/<int:pk>/', suppliers.InvoiceView, name='invoice_edit'), path('trips/', suppliers.trips, name='supplier_trip'), path('printinvoice/<int:pk>/', suppliers.PrintInvoice, name='invoice_print'), ], 'classroom'), namespace='suppliers')), path('shipper/', include(([ path('editprofile/', teachers.ShipperUpdateView.as_view(), name='update_shipper'), path('freight/', teachers.QuizListView.as_view(), name='quiz_change_list'), path('assigned/', teachers.AssignedListView.as_view(), name='assigned_list'), path('activetrucks/<int:pk>/', teachers.take_quiz, name='take_quiz'), path('activetrucks/', teachers.QuizListView1.as_view(), name='active_trucks'), path('rtd-items/', teachers.rtd_items.as_view(), name='rtd-items'), # this fucked up code was written by chirag gulati path('dispatched-items/', … -
How should I add permissions to a model correctly?
When users register, then I add a permission to view content. However, the added permission is classing with Django default. I'd like to add a view permission, but do not know how. Once, users get this permission, they can view specialized content. class Viewing(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) view_content = models.BooleanField(default=False) order_id = models.CharField(max_length=250, blank=True) purchases = models.IntegerField(default = 0, blank=True) class Meta: ordering = ['user'] permissions = (("view_content", "Content Access"),) def __str__(self): return f'{self.user} ({self.view_content})' django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: c(auth.E005) The permission codenamed 'view_content' clashes with a builtin permission for model 'mymodel.Viewing'. -
Python avoiding using for loop or need shorten the code base
I have write python code and it has too many for loop, as a result, my code readability is too low and pylint star too low. I am finding a way to solve same with fewer line of code. here you go for my snippet: numberlist = [1,3,5] stringlist = ['a', 'b', 'c'] id = '458' numbered_string = [] for n, s in numberlist, stringlist: num_str = "{}{}".format( n, s, id, ) numbered_string.append(num_str) codes = [] for n,s, sn in numberlist, stringlist, numbered_string: code = make_code( n, s, sn ) codes.append(code) print(codes) Ignore the function make_code() , or let's assume the make_code() is def make_code(n,s, sn): return str(n) + str(s) + str(sn) Can anyone help me shorten the snippet?, please ignore the function. I want to improve this code much better and high readability, too many instance is not a solution. -
form not submitting on click register django
On click register button it no posting data to database. def register(request): if request.method =="POST": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() username = form.clearned_data.get('username') messages.success(request, f"New Account Created: {username}") login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("/") form = UserCreationForm return render(request, 'register.html', {"form":form}) it refresh and still open register.html. instead to redirect to home page. pls i need help i expect it to redirect to home, return to home page. -
Django/Python caching solution that I can access with complex keys rather than only strings
It is my understanding that all caching solutions for Django/Python are essentially based on key/value dictionaries. cache.store(“key”, “value”) cache.get(“key”) # <- “value” I understand there are decorators and other abstractions that allow you to store in cache based on the view function, but they’re agnostic towards the inputs of this function (POST/GET parameters, for example). Here’s my problem: I need to cache results of computations of complex sets of inputs, including (but not limited to), the user that’s performing the request, dictionaries, booleans, ecc... I could, in theory, serialize these inputs into a string and use this string as the key for caching but I was wondering if there are some pre-made solutions to solve this problem. Something like this: def my_view(request): output = cache.get(request, None) if output is None: output = complex_stuff(request) cache.store(request, output) Or, even better, where I can use an arbitrary dictionary as a key, instead of a string. -
Django: view formatted sql in console
I want to see formated sql queries in the console of Django while developing I have tried adding the below code to settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['console', ], }, }, } Now whenever there is any sql query it shows in the django console. But its not well formatted. So how can i see the formatted sql queries instead of single line -
how to read source code of django-rest-framework, or any other python library
I am learning django-rest-framework. trying to figure out what's the diffrent bettwen update and partial update in modelviewset,so I decided to read source code, but source code in github with a lot of inherit relationships are difficult to read. I found a website http://ccbv.co.uk/ when I learning about django,that really helpful to read source code, and now I found http://www.cdrf.co/ although this website pretty much the same as first one, but seems got a issue,no __init__. anyway, I am just wanna know how experienced programmer learning about new library. and read and understand those source code efficiently? -
How to order Django queryset by an encrypted field and use the result in ModelForm
I'm using django-encrypted-model-fields to encrypt selected model fields. As described in the documentation (https://pypi.org/project/django-encrypted-model-fields/) sorting and filtering by values contained in encrypted fields is not supported. And yet, I would like to provide to users the possibility to select from an ordered drop-down list in the admin ModelForm as the following example attempts to do, although the the values are stored in encrypted form: models.py class ProjectActivity (models.Model): abbreviation = EncryptedCharField(max_length=20) project = models.ForeignKey("Project", on_delete=models.CASCADE) class Rule (models.Model): name = EncryptedCharField(max_length=100) activities = models.ManyToManyField('ProjectActivity', related_name="rules") admin.py class RuleAdmin(admin.ModelAdmin): form = RuleForm forms.py class RuleForm(forms.ModelForm): class Meta: model = Rule fields = '__all__' def __init__(self, *args, **kwargs): super(RuleForm, self).__init__(*args, **kwargs) activities_queryset = ProjectActivity.objects.filter(project=current_project) # activities should be decrypted by now self.fields['activities'].queryset = activities_queryset.order_by('abbreviation') The above code loads and decrypts the activities first and then tries to sort them but the result is not correct. sorted(), as in the following code orders correctly self.fields['activities'].queryset = sorted(activities_queryset , key=lambda o: o.abbreviation) however the result is a list and not a dataset and thus the templating system runs into the following AttributeError: 'list' object has no attribute 'all' Any ideas how to solve or bypass the problem? -
How to mark task as complete using JavaScript, AJAX in a Django App
I am trying to implement a todo(goal) list within my Django App. I am able to add steps to my todo list, however I cannot figure out how to mark the step as complete (set the 'done' boolean field true). The step model I have includes a boolean field which I am trying to set to true when submitting the checkmark form. I've tried to use a variation of my new step form mark the step as complete but I've been unsuccessful so far. <form class='check_Mark' method='post' data-goal={{goal.pk}} data-step={{step.pk}} action="{% url 'check_mark' goal.pk %}">{% csrf_token %} <button type="submit"> Mark Complete </button> </form> function qAll (selector) { return document.querySelectorAll(selector) } const checkMark = qAll('.check_Mark') checkMark.forEach(item => { item.addEventListener('submit', function (e) { e.preventDefault(); console.log(item.dataset.step) console.log(item.dataset.goal) $.ajax({ type: 'POST', url: item.action, data: { 'goal': item.dataset.goal, 'step': item.dataset.step, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, dataType: 'json', success: function (data) { console.log('Success') location.reload(); } }); }); }) path('goal/', core_views.goal_list_view, name='user-profile'), path('goal/add', core_views.add_new_goal, name='add_goal'), path('goal/add_step/<int:pk>', core_views.add_new_step, name='add_step'), path('step/<int:pk>/', core_views.check_mark, name='check_mark'), @login_required def check_mark(request, pk): from core.forms import CheckListForm from django.views.generic.edit import CreateView if request.method == "POST": form = CheckListForm(request.POST) if form.is_valid(): done = form.save(commit=False) done.person = Person.objects.get(user=request.user) done.goal = get_object_or_404(Goal, pk=pk) done.step = get_object_or_404(Step, pk=pk) done.done = True form.save() … -
What can be done to fix Heroku's H10 error?
I am trying to launch a simple portfolio website using Heroku but everytime I run the app I get the H10 error. What can I do to fix it? I've had various errors throughout the process, which I've managed to fix. But this recent error, H10, I can't seem to figure out what's going on. In the logs, I can see where the app is asking to me apply the migration for 17 files. I run python manage.py migration and it says there's nothing to update. I then try to do heroku run python manage.py migration and it runs succesfully. Then, I do the git add ., git commit -m "comment" and lastly git push heroku master. This what happens when it runs. Enumerating objects: 35, done. Counting objects: 100% (35/35), done. Delta compression using up to 8 threads Compressing objects: 100% (24/24), done. Writing objects: 100% (26/26), 3.76 KiB | 961.00 KiB/s, done. Total 26 (delta 16), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.7.3 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Found python-3.6.8, removing remote: -----> … -
Multiple image upload in django using multiupload
I have been working on this for a while. I am trying to set-up a listing site where users can upload multiple images per post and are limited on the number of images they can upload and so-far this package seems to be perfect for my use-case. I did have to create a fork to get it to work with the newer version of django, where I added renderer=None to line 23 of field.py in the def render. That fixes the error and allows me to view the form, but on submission I get a 'list' object has no attribute 'name' error. I used this answer to get to this point. Any help would be appreciated! models.py class Listing(models.Model): description = mdoels.TextField(blank=True) track_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Photo(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE) file=models.FileField(upload_to='images', verbose_name = 'Photos') forms.py class ListingForm(forms.ModelForm): photos = MultiImageField(min_num=1, max_num=4) class Meta: model = Listing fields = ['description',] def save(self, commit=True): photos = self.cleaned_data('photos') instance = Super(ListingForm, self).save(commit) for each in photos: Photo.objects.create(file = each, listing = instance) return instance views.py class AddForm(CreateView): model = Listing template_name = 'marketplace/listing_create.html' form_class = ListingForm success_url = 'index' def form_valid(self, form): instance = form.save(commit = False) instance.user = self.request.user …