Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
import error: module properly installed, pycharm congfigured for virtualenv, was working
I have set up my pycharm to point to my virtualenv I have properly installed the module in this case its requests I have properly used the module. This is a case of " it just stopped working" here is the code that the module requests is being used in import requests from suitsandtables.settings import googlemapsgeocodeurl, googlemapsgeocodekey class VenueServices: def getvenueaddresscoordinates(self,address): url = googlemapsgeocodeurl + VenueServices.prepareaddress(self,address) + googlemapsgeocodekey r = requests.get(url).json() r = r['results'][0]['geometry']['location'] return r def prepareaddress(self, address): convertedaddress =[] addressstring = '' for add in address: add = add.replace(' ', '+') convertedaddress.append(add) addressstring = convertedaddress[0] + ',+' + convertedaddress[1] + ',+' + convertedaddress[2] return addressstring and the error: File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/suitsandtables/urls.py", line 18, in <module> from venues.urls import * File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/venues/urls.py", line 2, in <module> from views import UnapprovedVenueApplicationDetail, DeclineDestroyVenueApplication, VenueAddressLatLng, UnapprovedVenueApplicationList, CreateUnapprovedVenue, CreateApprovedVenue,RetreiveEditDeleteApprovedVenue File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/venues/views.py", line 8, in <module> from services import VenueServices File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/venues/services.py", line 1, in <module> import requests ImportError: No module named requests -
Django - File remove button for InlineFormSet not working
I have 2 models, OwnerListing and OwnerListingPhoto, the latter is a ForeignKey to the former. I'm using InlineFormset to allow the user to edit an existing OwnerListing with all of its respective OwnerListingPhoto's. On the site, the formset is shown like this. Everything else is working fine, except the delete function. When you check the 'Delete' checkbox and submit the form, the form is successfully submited, but the photo is not deleted. What's going on in my code that is causing this? def fsbo_edit_listing(request): listing = OwnerListing.objects.get(id=int(request.GET.get('id'))) PhotoFormSet = inlineformset_factory( OwnerListing, OwnerListingPhoto, fields=('photo',), widgets={ 'photo': ClearableFileInput(attrs={'class': 'btn btn-outline-secondary form-control'}) } ) if request.method == 'POST': form = OwnerListingForm(request.POST, instance=listing) photo_formset = PhotoFormSet(request.POST, request.FILES, instance=listing) if form.is_valid() and photo_formset.is_valid(): form.save() for i in photo_formset: if i.instance.pk and i.instance.photo == '': i.instance.delete() elif i.cleaned_data: temp = i.save(commit=False) temp.listing = form.instance temp.save() return redirect('dashboard') else: if listing.user == request.user: form = OwnerListingForm(instance=listing) photo_formset = PhotoFormSet(instance=listing) else: raise Http404('Not a valid request') return render(request, 'fsbo_create_listing.html', {'form': form, 'photo_formset': photo_formset}) HTML: {{ photo_formset.management_form }} {% for form in photo_formset %} <div class="col-sm-6 col-xl-4 mb-3 p-1" style=""> <div class="col-12 border border-dark rounded p-2"> {{ form }} </div> </div> {% endfor %} -
Expected view to be called with a URL keyword argument named "user_token"
I am using Django Rest Framework and here is my view: class DeleteUserView(generics.DestroyAPIView): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer queryset = User.objects.all() lookup_field = 'user_token' and my urls.py: from django.urls import path from .views import CreateUserView, DeleteUserView urlpatterns = [ path('add_user/', CreateUserView.as_view()), path('delete_user/', DeleteUserView.as_view()), ] serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('user_token',) I am trying to delete user by specific token but it doesn't work... -
Django ON UPDATE setting for Foreign Keys?
Why does Django not have an ON UPDATE setting for foreign keys? The ForeignKey model only has on_update. -
Parent page option keeps appearing
I'm working on a Python/Django/Wagtail project. At some point when creating an Article it could go under the Articles index model or the Partners index model. I deleted all of the Partners traces in the code, and the Article model only has this: parent_page_types = ['btcmag.ArticleIndexPage'] However when creating an Article, I still get the same screen showed above. Am I missing some step? -
Pyinstaller subprocess exception When running on windowed mode
I'm using pyinstaller to create my application.In my django app, I'm using subprocess. When i execute pyinstaller in noconsole mode its throwing errors. Error log: Traceback (most recent call last): File "site-packages\django\core\handlers\base.py", line 149, in get_response File "site-packages\django\core\handlers\base.py", line 147, in get_response File "crumbs_tableau\views.py", line 1603, in parser File "site-packages\django\shortcuts.py", line 67, in render File "site-packages\django\template\loader.py", line 96, in render_to_string File "site-packages\django\template\loader.py", line 43, in get_template django.template.exceptions.TemplateDoesNotExist: helpers/error.html Internal Server Error: / Traceback (most recent call last): File "crumbs_tableau\views.py", line 286, in parser File "crumbs_tableau\views.py", line 248, in mac_list File "subprocess.py", line 336, in check_output File "subprocess.py", line 403, in run File "subprocess.py", line 667, in __init__ File "subprocess.py", line 905, in _get_handles File "subprocess.py", line 955, in _make_inheritable OSError: [WinError 6] The handle is invalid During handling of the above exception, another exception occurred: Traceback (most recent call last): File "site-packages\django\core\handlers\base.py", line 149, in get_response File "site-packages\django\core\handlers\base.py", line 147, in get_response File "crumbs_tableau\views.py", line 1603, in parser File "site-packages\django\shortcuts.py", line 67, in render File "site-packages\django\template\loader.py", line 96, in render_to_string File "site-packages\django\template\loader.py", line 43, in get_template django.template.exceptions.TemplateDoesNotExist: helpers/error.html Not Found: /static/parser/bootstrap.css.map -
Incomplete json structure - no count/next/previous/results field
like many times before, im trying to send data from my Django backend to my Ionic mobile app. This time, however, for some reason, the .jsons im parsing are coming out incomplete. A complete .json: {"count":1,"next":null,"previous":null,"results":[{"codigo":"qwe","area":"ewq","especies":[],"id":1}]} My incomplete .json: [{"nome_ficheiro":"1520529086252.jpg","id":26,"especie":"Ameijoa Branca","zona":"L6","data":"09/06/2018"}] IONIC is struggling with identifying what I'm parsing as a .json, which makes sense since there is no "results" field. Here are the relevant snippets of my django code: Views.py (both Views are doing the same thing! This is just me trying out different approaches!) class resultUploadViewSet(viewsets.ViewSet): def list(self, request, nome_ficheiro): queryset = labelResult.objects.all() nome = nome_ficheiro answer = queryset.filter(nome_ficheiro=nome) serializer = resultSerializer(answer, many=True) return Response(serializer.data) class resultUploadView(APIView): serializer_class = resultSerializer def get(self, request, nome_ficheiro): queryset = labelResult.objects.all() nome = nome_ficheiro answer = queryset.filter(nome_ficheiro=nome) serializer = self.serializer_class(answer, many=True) return Response(serializer.data) Models.py class labelResult(models.Model): nome_ficheiro = models.CharField(max_length=120) especie = models.CharField(max_length=120) zona = models.CharField(max_length=120) data = models.CharField(max_length=120) Urls.py urlpatterns = [ url(r'results/(?P<nome_ficheiro>.+)/$', resultUploadViewSet.as_view({'get': 'list'})), url(r'results1/(?P<nome_ficheiro>.+)/$', resultUploadView.as_view())] Serializers.py class resultSerializer(serializers.ModelSerializer): class Meta: model = labelResult fields = ('nome_ficheiro','id','especie','zona', 'data') Any idea why my .jsons are coming out incomplete? -
Django - How can I open multiple stored files and render them as HTML?
I have a user account that can create a model called experiment. Within this model, it can store files: HTML, JS, and CSS. It stores them in the server. My issue right now is trying to figure out how to approach this problem of rendering the HTML file on a page. Do I try to create a view that has an HTTP response of the file? Is there a better way? -
import requests fail. pycharm, project interpreter set up to us virtual env
I am receiving a error that requests is not installed in python after I have installed it, and used it. I have successfully installed requests inside my virtual environment I have successfully pointed pycharms project interpreter to the virtual environment using this tutorial: http://exponential.io/blog/2015/02/10/configure-pycharm-to-use-virtualenv/ I have successfully used requests. This is literally a case where "it just stopped working" This is a django project. Things I have done recently that shouldn't effect this issue, but just in case Made changes to my models changed urls changed views the code that uses requests looks like this: import requests from suitsandtables.settings import googlemapsgeocodeurl, googlemapsgeocodekey class VenueServices: def getvenueaddresscoordinates(self,address): url = googlemapsgeocodeurl + VenueServices.prepareaddress(self,address) + googlemapsgeocodekey r = requests.get(url).json() r = r['results'][0]['geometry']['location'] return r def prepareaddress(self, address): convertedaddress =[] addressstring = '' for add in address: add = add.replace(' ', '+') convertedaddress.append(add) addressstring = convertedaddress[0] + ',+' + convertedaddress[1] + ',+' + convertedaddress[2] return addressstring the error I am getting: File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/suitsandtables/urls.py", line 18, in <module> from venues.urls import * File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/venues/urls.py", line 2, in <module> from views import UnapprovedVenueApplicationDetail, DeclineDestroyVenueApplication, VenueAddressLatLng, UnapprovedVenueApplicationList, CreateUnapprovedVenue, CreateApprovedVenue,RetreiveEditDeleteApprovedVenue File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/venues/views.py", line 8, in <module> from services import VenueServices File "/home/rickus/Documents/softwareProjects/211hospitality/suitsandtables/backend/virtualsuits/suitsandtables/venues/services.py", line 1, in <module> import requests … -
Generating an API blueprint documentation from Django/DRF code
Is there any lib/parser which can generate API blueprint documentation (apiary) from Django + Django Rest Framework code? Eg: class UserView(...): """ ## Users list [GET /users] + Request (application/json) ... + Response (application/json) ... """ class UserSerializer(...): """ ## User (object) + id (string) + username (string) + ... """ -
Wagtail admin password reset doesn't work
According to the server logs email has been sent: [08/Mar/2018 17:07:50] "GET /admin/password_reset/ HTTP/1.0" 200 4304 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Password reset From: correct.email@address.com To: narunas@example.com Date: Thu, 08 Mar 2018 17:08:01 -0000 Message-ID: <20180308170801.3122.49315@linux-host> Please follow the link below to reset your password: http://example.com/admin/password_reset/confirm/MQ/4ub-ba21a21a92b51d01e139/ Your username (in case you've forgotten): narunas ------------------------------------------------------------------------------- [08/Mar/2018 17:08:01] "POST /admin/password_reset/ HTTP/1.0" 302 0 [08/Mar/2018 17:08:01] "GET /admin/password_reset/done/ HTTP/1.0" 200 3662 However tcpdump show contradicting results, thus email hasn't been sent: # tcpdump -i any -fn port 587 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on any, link-type LINUX_SLL (Linux cooked), capture size 262144 bytes I'm using the following django settings: WAGTAILADMIN_NOTIFICATION_FROM_EMAIL = 'correct.email@address.com' DEFAULT_FROM_EMAIL = 'correct.email@address.com' EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com' EMAIL_HOST_USER = '******************' EMAIL_HOST_PASSWORD = '******************' EMAIL_USE_TLS = True EMAIL_PORT = '587' Any idea what's wrong? -
How to save images from RTF editor in Django project?
I have been able to use Alloy Editor (a fork of CKEditor) and save the formatted texts in Django model. I have used AJAX to capture the input and save the data with the following code. $(document).ready(function() { $('#create_form').on('submit', function(e) { e.preventDefault(); $.ajax({ url : '/create/', type : 'POST', data : { title : $('#id_title').val(), body : $('#id_body').html() }, success : function() { $(location).attr('href', '/'); } }) }); }); However, when I select an image in the editor and hit the save button I am shown a 400 bad request error in the console. I am guessing that for the image to be used within the article I am trying to save I have to upload the image in the media folder and put a link to that uploaded image in the place where I have placed the image in the RTF editor. How can I do this? -
EXE application created using pyinstaller running in memmory two times
I used py installer to make EXE application package from my django web-app. I could run my application perfectly, But when i run application inside process this application running more than one time. This will leads to memory leakage that i cant compromise with. Used Pyinstaller 3.3.1 python 3.6 Django 1.9 -
How to submit tags in bootstrap tagsinput with form
I am trying to submit a form with bootstrap tagsinput, But having some issues . At views.py when I try to get the tags that are entered in tagsinput, I get an empty list. Earlier I tried getting tags in jquery using this command $("#tagbar").tagsinput('items') and made a POST request with Ajax to transfer values to the views.py and it worked perfectly. But it doesn't works with form. How can we get the list of tags in views.py. index.html <form method="post" enctype="multipart/form-data" action="/get_data/"> <input type="text" id="tagbar" /> <button type="submit">Submit</button> </form> views.py @csrf_exempt def get_data(request): if request.method == 'POST': tags = request.POST.getlist('tagbar') print(tags) return render(request, "index.html") -
Setting DEFAULT_FILE_STORAGE in settings.py triggers "TypeError: Unicode-objects must be encoded before hashing"
I'm setting up my app to work with AWS. I can upload my static files by running python manage.py collectstatic however when I follow the instructions and set my DEFAULT_FILE_STORAGE for my my media files I get this error: "TypeError: Unicode-objects must be encoded before hashing". If I comment out DEFAULT_FILE_STORAGE = app.aws.utils.MediaRootS3BotoStorage the error message goes away. I've searched relentlessly but I haven't found anything to point me in the right direction. Could this be an issue with the packages I've installed? Packages: boto3==1.6.4 botocore==1.9.4 Django==2.0.2 django-photologue==3.8.1 django-sortedm2m==1.5.0 django-storages==1.6.5 docutils==0.14 ExifRead==2.1.2 jmespath==0.9.3 Pillow==5.0.0 psycopg2==2.7.4 python-dateutil==2.6.1 python-decouple==3.1 pytz==2018.3 s3transfer==0.1.13 six==1.11.0 Here are the logs: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x1103e3ea0> Traceback (most recent call last): File "/dev/app/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/dev/app/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/dev/app/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/dev/app/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/dev/app/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/dev/app/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/dev/app/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/dev/app/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", … -
Django why request.method=='GET' when refreshing the page
I want to have some search boxes on my page and my related codes are like below, my problem is why when i refresh the page the if clause: " if request.method=='GET':" executes without i click on any button ? def allstocks_view(request): if request.method=='GET': question_set =Stocks.objects.all().filter(confirm=_('approved') ) name=request.GET.get('namesearch') number=request.GET.get('numbersearch') brand=request.GET.get('brandsearch') if name is not None : question_set = question_set.filter(name__icontains = name) if number is not None : question_set = question_set.filter(number__icontains = number) if request.GET.get("brandsearch"): question_set = question_set.filter(brand__icontains = brand) print(">>>>>>>>>>>>>>>>>>>>") print(question_set) template : <form method="get"> {% csrf_token %} <div class=""> <label for="namesearch">Name</label> <input type="text" name="namesearch" > <label for="numbersearch"> Number</label> <input type="text" name="numbersearch" > <label for="brandsearch"> Brand</label> <input type="text" name="brandsearch" > <label for="brandsearch"> City</label> <input type="text" name="citysearch" > <input type="submit" name="search" value="Search"> </div> </form> -
Querying all objects including soft deleted ones of a SoftDeletableModel
I'm try to get rid of home-brew solution to favor more standard ones. My previous pattern: class MarkDeleteManager(models.Manager): use_for_related_fields = True def get_queryset(self): if "instance" in self._hints: return super(MarkDeleteManager, self).get_queryset() return super(MarkDeleteManager, self).get_queryset().filter(deleted=False) def all_with_deleted(self): return super(MarkDeleteManager, self).get_queryset() def deleted_set(self): return super(MarkDeleteManager, self).get_queryset().filter(deleted=True) def using(self, *args, **kwargs): ''' if a specific record was requested, return it even if it's deleted ''' return self.all_with_deleted().using(*args, **kwargs) I'd like to replace this with django-model-util's SoftDeletableModel but I don't see any all_with_deleted like functionality in the SoftDeletableManagerMixin - it only overrides get_queryset and that's it. My architecture is decentralized, and when I notify other nodes about soft deletions I need to access those. -
python django filter links
I am trying filter the links and sometimes i get this error. Object of type QuerySet is not JSON serializable I am trying to avoid to serialize the object...because it's not going to be arranged correctly. Hope you see what i mean. This is part of my views.py results_data = [] result_dates = [] for alert in pages_qs.object_list: domain = Crawlerdomains.objects.get(pk=alert.domain_id) CrwlPage = get_page_model(domain.tablename) try: q = request.GET.get('q', None) if q: pg_link = CrwlPage.objects.filter(links__icontains=str(q)) else: pg_link = CrwlPage.objects.get(pk=alert.crwlpgid).links except CrwlPage.DoesNotExist: pg_link = '' alert_dict = { 'id_dmn': alert.domain_id, 'id': alert.pk, 'CrwlPgID': alert.crwlpgid, 'pg_link': pg_link, 'New_CronHistID': alert.new_cronhistid, 'Old_CronHistID': alert.old_cronhistid, 'Website': alert.website, 'LastCrwlDate': str(alert.lastcrwldate), 'PrevCrwlDate': str(alert.prevcrwldate), } results_data.append(alert_dict) and this is how i call it in urls.py urlpatterns = [ url(r'^alert/report/$', views.get_alerts, name='report'), ] basically if i m going to serialize it i m going to have json obj in json... i am trying to extract the links when i q for links. https://example.com/alert/report/?q=word I have tried a lot of things...this is the last thing i have tried. Basically using alert.id i want to check the link of that specific id for the word (Example the word: europe ) and if found....return the link in that json object...else return empty...and if no … -
Python | Docker | Django | django.core.exceptions.ImproperlyConfigured Error
I'm trying to run a python file that is inside a container however I'm getting the following exception: Traceback (most recent call last): File "/tmp/e2esetup.py", line 2, in <module> django.setup() File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Code being run in docker: docker exec -it $DOCKER_ID python /tmp/e2esetup.py My code: import django django.setup() from django.conf import settings from django.contrib.auth.models import User from apps.account.models import Profile from apps.organisation.models import Organisation .... #rest is fine for sure I'm new to django and docker, from what I can tell I need to set the environment however I don't know how, running through manage.py does this for you or something, so if I were to run a python file through the interpreter, I have to do this manually, however I dont know how. I also read that I need to pipe the docker environment somehow, but I'm not sure what that means either, any help is appreciated! -
Test case data stays in Django development database Selenium
I have a simple form for registering new user. I wrote a test case for it. It looks as follows: class AccountTestCase(LiveServerTestCase): def setUp(self): self.selenium = webdriver.Firefox() super(AccountTestCase, self).setUp() def tearDown(self): self.selenium.quit() super(AccountTestCase, self).tearDown() def test_register(self): selenium = self.selenium #Opening the link we want to test selenium.get('http://localhost:8000/register/') #find the form element first_name = selenium.find_element_by_id('id_first_name') last_name = selenium.find_element_by_id('id_last_name') username = selenium.find_element_by_id('id_username') email = selenium.find_element_by_id('id_email') password1 = selenium.find_element_by_id('id_password1') password2 = selenium.find_element_by_id('id_password2') submit = selenium.find_element_by_id('btn_signup') #Fill the form with data first_name.send_keys('abc') last_name.send_keys('abc') username.send_keys('abc') email.send_keys('abc@gmail.com') password1.send_keys('abcabcabc') password2.send_keys('abcabcabc') #submitting the form submit.send_keys(Keys.RETURN) #check the returned result self.assertTrue('Success!' in selenium.page_source) When I ran the test case for the first time it passed with flying colors, but on the second run it failed. After little investigation I realized a user with credentials from test cases is already created in my database. Thus, when I ran test case for second time it failed to create a new user, as user with these details is already present. (I can see user from Django admin). I believe this is not the expected behaviour of LiveServerTestCase(or any type of test case). In setup, a temporary database is created, test case is ran on it, and destroyed in tearDown phase. I want … -
django default profile image
i'm trying to setup a default profile image url using an image on my static files . when i have a profile image using this work fine <img src="{% if user.avatar %}{{ user.avatar.url }}{% endif %}"> and when i try the default image <img src="{% static 'img/default-avatar.png' %}"> works fine as well but when i clear the image trying to show the default image i get ValueError at : The 'avatar' attribute has no file associated with it. #my model class User(AbstractUser): #otherstuff avatar = models.ImageField(null=True ,blank=True) #morestuff #template <img src="{% if user.avatar %}{{ user.avatar.url }}{% else %}{% static 'img/default-avatar.png' %} {% endif %}"> -
Make new custom view at django admin
Sorry, I am still new at django. I want to make custom view at admin site that is not related to my model. I have read the documentation (https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_urls), but does not work. Reading some tutorials does not work too... Here is what I tried: admin.py from django.contrib import admin from django.urls import path from .models import Question from django.http import HttpResponse class CustomAdminView(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() my_urls = [ path(r'^my_view/$', self.admin_view(self.my_view)) ] urls = my_urls + urls return urls def my_view(self, request): return HttpResponse("Hello, world.") admin.site.register(Question) urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include, url admin.autodiscover() urlpatterns = [ path(r'polls/',include('polls.urls')), path('admin/', admin.site.urls), ] when I go to admin/my_view the result is 404 not found. I tried by extending the AdminView too. admin.py from django.contrib.admin import AdminSite from django.urls import path from .models import Question from django.http import HttpResponse class CustomAdminView(AdminSite): def get_urls(self): urls = super().get_urls() my_urls = [ path(r'my_view/', self.admin_view(self.my_view)) ] urls = my_urls + urls return urls def my_view(self, request): return HttpResponse("Hello, world.") custom_admin = CustomAdminView() custom_admin.register(Question) urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include, url from polls.admin import custom_admin admin.autodiscover() urlpatterns = [ path(r'polls/',include('polls.urls')), path('admin/', … -
Perform Custom logic after django-paypal successful transaction
I'm working on a project in which I'm using Python(3.6) and Django(1.10), in this project I need to implement PayPal Express Checkout to receive payments.Actually, we are selling certifications from our organizations.The certificate will be generated automatically after successful payment transaction from PayPal. The problem is, I don't know how to handle signals after successful payment from PayPal. Here's what I have tried: From views.py: def payment_process(request): paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'amount': '5.00', 'item_name': 'Certificate from INC.', 'currency_code': 'USD', 'ret urn_url': 'http://127.0.0.1:8000/users/done', 'cancel_return': 'http://127.0.0.1:8000/users/cancel', 'isPayment': 'True', } valid_ipn_received.connect(show_me_the_money) form = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'users/generateCert.html', {'form': form}) @csrf_exempt def payment_done(request): print(valid_ipn_received.connect(show_me_the_money)) return generate_certificate(request) @csrf_exempt def payment_canceled(request): return render(request, 'users/payment_canceled.html') def generate_certificate(request): template = get_template('users/certificate_template.html') minutes = int(request.user.tagging.count()) * 5 testhours = minutes / 60 hours = str(round(testhours, 3)) context = { "fullname": request.user.first_name + ' ' + request.user.last_name, "date": datetime.date.today(), "hours": hours, "today": "Today", } html = template.render(context) pdf = render_to_pdf('users/certificate_template.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" % "12341231" content = "inline; filename='%s'" % filename download = request.GET.get("download") if download: content = "attachment; filename='%s'" % filename response['Content-Disposition'] = content return response return HttpResponse("Not found") Here are my Templates: generateCert.html {% block content %} {% csrf_token %} … -
Trying to replace default HTML widgets
I'm making a framework to improve the development of an existing system. My main task was to make said system responsive, and we settled in using material design. we're using django version 1.9. We've tried a lot of existing frameworks (django material, grappelli, etc), but we decided to develop our own, because if we were to use an existing framework we'd have to hack the sh*t out of it, basically. The thing is, right now I need to be able to render HTML widgets so that materialize (the library we're using) displays them nicely. I know that, as far as what I've read (pretty much anywhere), this is not possible by default. So I've come up with two ways to do so (I implemented a quick and dirty version of the second and it works, kind of), but I find both of them to be extremely... not elegant. The first one consists on creating our own database fields, inheriting from the ones defined in django, overwriting the formfield method to use custom form fields (which we would create by inheriting from django's ones and making them use our custom widgets). I (clearly) haven't implemented this one because it seems to … -
How to pass custom elements list to the class attribute properly?
I have the line in my template: <div class="class1 class2 class3 {{ foo_classes }}"> If the foo_classes is empty I get class="class1 class2 class3 ". What I want to get is class="class1 class2 class3" with no additional space at the end of the classes list. <div class="class1 class2 class3{{ foo_classes }}"> If I delete the space (look at the line above) then I get class="class1 class2 class3class4 class5", which is no better. How do I pass additional classes to avoid getting unnecessary space at the end of the classes section if the foo_classes is empty?