Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dependencies on Media class in Django
I have a simple ModelAdmin, which defines a Media class and this class includes some JavaScript class ExerciseAdmin(NestedPolymorphicModelAdmin): class Media: js = ( 'exercises/ck-editor-dynamic-init.js', ) I'd like to use django.jQuery in this script, but the problem is that when thi script is injected to the admin site django.jQuery is not initialized yet. Here is my workaround, but it's ugly: let loading = setInterval(function () { if (django.jQuery !== undefined) { loading = clearInterval(loading); (function ($) { $(document).on('formset:added', function newForm(event, row) { console.log(event); }); })(django.jQuery); } }, 100); I can imagine, that this is not the best way how to do it. Can somebody suggest any better? Thanks -
I am trying to make a specific query the contains sub-string comparison using row function
I am trying to make a query that joins 3 tables and contains conditions that use substring comparison. I am using row function I have tried filters but didn't know how to join more than one table This is the view.py def index(request): transportServices=TransportServices.objects.all() interFaceType= InterfaceType.objects.raw(''' SELECT it_pk,it_short_name from transport_services,interface_type,router WHERE rou_pk= 519342 and ts_rou_pk=rou_pk and ts_it_pk=it_pk and rou_last=1 and (it_short_name like 'GE%' or it_short_name like 'FE%' or it_short_name like 'TE%') order by it_short_name ''') print(interFaceType) if request.method == 'GET': connectionType = request.GET.get('ConnType') print(connectionType) #print(Router.objects.all()) return render(request,'posts/index.html',{'router': router}) This is model.py class Router(models.Model): rou_pk = models.AutoField(db_column='ROU_PK', primary_key=True) rou_st_pk = models.DecimalField(db_column='ROU_ST_PK', max_digits=10, decimal_places=0, blank=True, null=True) rou_name = models.CharField(db_column='ROU_NAME', max_length=20, blank=True, null=True) rou_last = models.BooleanField(db_column='ROU_LAST', blank=True, null=True) class TransportServices(models.Model): ts_pk = models.AutoField(db_column='TS_PK', primary_key=True) # Field name made lowercase. ts_ts_pk = models.DecimalField(db_column='TS_TS_PK', max_digits=10, decimal_places=0, blank=True, null=True) # Field name made lowercase. ts_rou_pk = models.DecimalField(db_column='TS_ROU_PK', max_digits=10, decimal_places=0, blank=True, null=True) # Field name made lowercase. # ts_spe_pk = models.DecimalField(db_column='TS_SPE_PK', max_digits=10, decimal_places=0, blank=True, null=True) # Field name made lowercase. # ts_at_pk = models.DecimalField(db_column='TS_AT_PK', max_digits=10, decimal_places=0, blank=True, null=True) # Field name made lowercase. ts_it_pk = models.DecimalField(db_column='TS_IT_PK', max_digits=10, decimal_places=0, blank=True, null=True) # Field name made lowercase. class InterfaceType(models.Model): it_pk = models.AutoField(db_column='IT_PK', primary_key=True) # Field name made lowercase. #it_it_pk … -
Check url status without opening it
At Now when url is opened (without a slash - example.com/blog), a slash is automatically added at the end (there are 301 redirects). The question is, can I somehow do it so that the check first goes to see if the page exists (without a slash - example.com/blog). If so, open it. If not, then check whether the page exists with a slash (only without 301 - example.com/blog/). If so, then redirect 301, and if not, then throw 404. Now just if there is no page (example.com/blog), then a slash is added to the end first (example.com/blog/), 301 redirects go and only then a 404 error is thrown. In this case, the 404 error must be thrown immediately, without a 301 redirect. The dispatch was rewritten as follows. def is_normal_slash_count(url): temp_url = url slash_count = 0 while temp_url.endswith('/'): slash_count += 1 temp_url = temp_url[:-1] return (slash_count == 1, slash_count) def replace_bad_slash(url, slash_count): if slash_count == 2: return url.replace('//', '/') return url.replace('/'*(slash_count-1), '') def normalize_url(url): if len(url) > 1: if not url.endswith('/'): return url + '/' # replace the url like /contacts//// to /contacts/ good_slash, slash_count = is_normal_slash_count(url) if not good_slash: url = replace_bad_slash(url, slash_count) return url def is_bad_url(url): if len(url) … -
Django Login using function error: join() argument must be str or bytes, not 'User'
I'm using Django 2.2.4 with this implementation for a login function def login_ajax(request): response = {'complete': False} if request.method == 'POST': data = json.loads(request.body) email, password = data['email'], data['password'] user = authenticate(request, username=email, password=password) if user is None: #try with email user = authenticate(request, email=email, password=password) #both checks done so invalid if user is None: response['error'] = 'Username/Email and Password Combination Failed.' else: print(user.id) login(request, user) response['complete'] = True else: response['error'] = 'no post data found' return HttpResponse( json.dumps(response), content_type="application/json" ) which can login with username/email based on Django's documentation but it throws this error TypeError at /login-ajax join() argument must be str or bytes, not 'User' Request Method: POST Request URL: http://127.0.0.1:8000/login-ajax Django Version: 2.2.4 Python Executable: C:\Users\samuel.irungu\Envs\chuify\Scripts\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\samuel.irungu\\code\\chuify', 'C:\\Users\\samuel.irungu\\Envs\\chuify\\Scripts\\python37.zip', 'C:\\Users\\samuel.irungu\\Envs\\chuify\\DLLs', 'C:\\Users\\samuel.irungu\\Envs\\chuify\\lib', 'C:\\Users\\samuel.irungu\\Envs\\chuify\\Scripts', 'c:\\users\\samuel.irungu\\appdata\\local\\programs\\python\\python37\\Lib', 'c:\\users\\samuel.irungu\\appdata\\local\\programs\\python\\python37\\DLLs', 'C:\\Users\\samuel.irungu\\Envs\\chuify', 'C:\\Users\\samuel.irungu\\Envs\\chuify\\lib\\site-packages'] Server time: Thu, 22 Aug 2019 10:03:59 +0000 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'common'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\samuel.irungu\Envs\chuify\lib\ntpath.py" in join 89. for p in map(os.fspath, paths): During handling of the above exception (expected str, bytes or os.PathLike object, not User), another exception occurred: File "C:\Users\samuel.irungu\Envs\chuify\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\samuel.irungu\Envs\chuify\lib\site-packages\django\core\handlers\base.py" in _get_response 115. … -
Get/Display API data at front end from an API created in Django using Django-REST-Framework in an HTML page or Template
I am working with Django for quite some time but only at the basic backend level. Now I have started using DRF or Django-REST-Framework for creating an API and this is a new thing for me. I have successfully made an API using it and tested it using Postman by hitting on the URL for the data. My app is sending data as JSON. Problem is that I am unable to find a tutorial or link to see how can I consume this API data at front end. How can I send requests to get the data and then make a form to save data at the back end. Models.py class Poll(models.Model): question = models.CharField(max_length=100) created_by = models.CharField(max_length=256) pub_date = models.DateTimeField(auto_now=True) serializers.py class PollSerializer(serializers.ModelSerializer): class Meta: model = Poll fields= ('created_by', 'question', 'pub_date') views.py class PollDetail(generics.RetrieveUpdateDestroyAPIView): serializer_class = serializers.PollSerializer queryset = Poll.objects.all() authentication_classes = [TokenAuthentication, BasicAuthentication] permission_classes = [IsAuthenticatedOrReadOnly] urls.py path('polls/<int:pk>/', views.PollDetail.as_view(), name='poll_detail_api'), Can someone help me with this? ALso How can I send information to authenticate users using Tokens saved in my DB? -
Deploy Django to Heroku (TemplateDoesNotExist)
I just deploy the project to Heroku, however the templates can't be found. Can someone help me out settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR,'Users/jay/Downloads/PJ/ecommerce/templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Error message: Exception Type: TemplateDoesNotExist Exception Value: list.html Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/template/loader.py in get_template, line 19 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.8 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Thu, 22 Aug 2019 09:51:24 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /app/Users/jay/Downloads/PJ/ecommerce/templates/list.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/templates/list.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/templates/list.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/crispy_forms/templates/list.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/accounts/templates/list.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/carts/templates/list.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/orders/templates/list.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/bootstrap4/templates/list.html (Source does not exist) -
Update records depending on fields - Django
I want to override the save method of a model in Django. Consider this model: class OtherClass(models.Model): name = models.CharField(max_length=255, blank=True, null=True) class MyClass(models.Model): admin = models.ForeignKey(OtherClass, on_delete=models.CASCADE) myfield1 = models.CharField(max_length=128) myfield2 = models.CharField(max_length=128) myfield3 = models.CharField(max_length=128, blank=True, null=True) myfield4 = models.CharField(max_length=128, blank=True, null=True) myfield5 = models.TextField(blank=True) What I want, is to update the model only if myfield5 is present in whatever form or view the user is filling. This is the current save method I have: def save(*args, **kwargs): fieldgroup = f"{self.myfield2}\n{self.myfield3}" self.myfield5 = f"{fieldgroup}\n{self.field1} {self.field4} {self.field5}" super().save(*args, **kwargs) Any ideas? Maybe it would be better to achieve this on a form rather than directly into the model? -
how do I write a test that would allow me to upload an image via DRF
I am trying to figure out how I can write a test for DRF that would allow me to upload an image file. uploading images does work fine via the the normal drf web view, but I am not sure the process to write a test for this. Below is what I currently have, however it is not currently working. When I do a trace on the response I am getting *** ValueError: Content-Type header is "text/html", not "application/json" Code below - doing a post to via Django's client for testcase def test_user_image_upload_post(self): header_admin = { "HTTP_AUTHORIZATION": "Token {}".format(self.token_admin), "Content-Type": "application/json" } img_1_path = Path("api/temp_files/temp1.gif") with open(img_1_path, 'rb') as tmp_file: tmp_file_str = base64.b64encode(tmp_file.read()).decode('utf-8') tmp_file_str_json = json.dumps(tmp_file_str) response = self.client.post( "api/images", data={ "gallery": "http://127.0.0.1:8000/api/galleries/{}/".format("2"), "img": tmp_file_str_json }, **header_admin ) import pdb; pdb.set_trace() #Not done yet self.assertEqual(tmp_image) Any help would be appreciated since this should return a 200 status code somehow. I know I am doing something wrong :-( -
How to show balance ZERO by default when someone new makes an account?
I have a page which shows a user how much balance he/she has. I put that balance in admin page. But when somebody makes an account first time, I want to show them their balance zero. How to do it? models.py class Balance(models.Model): amount = models.DecimalField(max_digits=12, decimal_places=2) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'Balance' def __str__(self): return f'{self.owner} Balance' views.py @login_required def balance(request): total = Balance.objects.get(owner=request.user) return render(request, 'nextone/balance.html', {'amount': total.amount}) HTML page <h2>Your Balance is Rs. {{amount}}</h2 -
Wagtail: Hook for changed order of subpages
Is there any way to hook into when changes are made to the ordering of subpages in the Wagtail admin? We would like to bust our caching for our menu component, but would like to keep the cacheclearing to a minimum preferably by hooking into when the change of ordering is made by posting to the set position endpoint. -
creating a delete button that deletes on the template but not in the django database
deleting an object from the template but not in the database.On clicking delete button the object will be removed from the template but updates the database with canceled. -
It is possible to get backend custom error message with d3.json?
I develop a django application where I have a d3js interactive tree. I use d3.json to get the tree data from the django view. I have create a decorator to check if user is logged to allowed the request or not. I have no problem when the user is logged but when the decorator return the jsonResponse with redirection url I have only the status error with the status description. I read d3js and promise documentation but I'm not found a answer to return a jsonresponse with my custom response. d3.json(d.data.url).then(function(data) { // process data no problem }, function(error){ console.log(error); }); def check_user_permission_js(view_function): @wraps(view_function) def wrapper(request, *args, **kwargs): if request.user.is_authenticated: return view_function(request, *args, **kwargs) messages.warning(request, "Your account doesn't have access to this page " + "or your session has expired. " + "To proceed, please login with an account that has access.") return JsonResponse({'not_authenticated': True, 'redirect_url': settings.LOGIN_URL,'data':[]}, status=500) return wrapper -
Using Django authenitcation with Angular frontend
I wish to use Django's inbuilt user authentication but my frontend is currently all Angular. The login/user status should be shown on the navbar with an option to login/logout. I can't find a guide on this anyway and what I have tried so far isn't giving me any results. I have tried rendering the nav bar in django by using 'app-nav-bar' to reference the angular component and I have also tried moving all the html from angular into django and using the verbatim tag to try and keep the angular functionality but these haven't worked. Navbar Component: <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a [routerLink]="['']" class="navbar-brand"> <img src="../static/ang/assets/images/logo.svg" alt="Logo" height="30px"> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse"> <div class="navbar-nav"> <a [routerLink]="['/view']" class="nav-item nav-link">View Projects</a> <a [routerLink]="['/manage']" class="nav-item nav-link">Manage Projects</a> </div> </div> </nav> Django template: //app-nav-bar had been going in here to test <app-root> <div class="container-fluid"> <div class="row align-items-center"> <div class="col text-center"> <div class="spinner-border p-5 m-5" role="status"> <span class="sr-only">Loading . . .</span> </div> </div> </div> </div> </app-root> I am expecting the navbar to have the same functionality in django as it does in angular but the links arent working or the navbar isnt … -
i want to call external bootstrap modal file using ajax in my django project but it is cannot working please give me a suppot
Here is my code which is calling the file shipper_modal.html file <script> $('.modalLink1').click(function(){ $.ajax({url: "shipper_modal.html", cache:false:function(result){ $(".modal-content").html(result); }) }) I want to ajax URL tag or other methods to call the shipper_modal file thanks in advance -
'ValueError: Required parameter not set' Django app following AWS configuration and Heroku deployment
I have just deployed my Django app to Heroku, having configured the app to store media files in an AWS S3 bucket. Everything was working correctly in the development server, but when I try to access pages containing these images in the Heroku-hosted version, I receive a ValueError informing me that the required parameter 'name' hasn't been set. A look through the traceback suggests that the supposedly nameless objects are the images. s3boto3 is also referenced. My configuration for AWS is detailed below: # settings.py AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') S3_USE_SIGV4 = os.environ.get('S3_USE_SIGV4') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # env.py os.environ.setdefault("AWS_ACCESS_KEY_ID", "**********") os.environ.setdefault("AWS_SECRET_ACCESS_KEY", "**********") os.environ.setdefault("AWS_STORAGE_BUCKET_NAME", "**********") os.environ.setdefault("AWS_S3_REGION_NAME", "eu-west-2") os.environ.setdefault('S3_USE_SIGV4', 'True') I've read suggestions that I may need to add an AWS_SESSION_TOKEN to the configuration, but I have no idea how to go about identifying mine. I've also read elsewhere that a session token isn't a necessary part of the configuration. I'm just looking for a steer so that I don't wind up wasting time attempting something which isn't going to fix the problem. -
Debugging while developing Django apps
I'm aware of pdb built-in Python library for debugging Python programs and scripts. However, you can't really use it for debugging Django apps (I get errors when I try to use it in views.py). Are there any tools that I can use when Django's traceback isn't helpful ? -
Dajngo https with a dev server
I'm trying to use SpeechRecognition/ webkitSpeechRecognition in my website, and thus need to run a dev server in django using https. I've taken the following steps: install and configure runserver_plus from django-extensions add the cert generated by this to my cas in ubuntu. # run server python3 manage.py runserver_plus --cert-file certs/localhost --reloader-interval 2 0.0.0.0:8000 then # to copy certificates: sudo mkdir /usr/share/ca-certificates/netia sudo cp certs/localhost.crt /usr/share/ca-certificates/netia/localhost.crt sudo chmod -R 755 /usr/share/ca-certificates/netia/ sudo chmod 644 /usr/share/ca-certificates/netia/localhost.crt sudo dpkg-reconfigure ca-certificates sudo update-ca-certificates I then restart everything to ensure changes have been accouted for, but the website is still not trusted on https://127.0.0.1:8000 and https://localhost:8000 What am I doing wrong? Note: awk -v cmd='openssl x509 -noout -subject' ' /BEGIN/{close(cmd)};{print | cmd}' < /etc/ssl/certs/ca-certificates.crt # gives: ... subject=CN = localhost subject=CN = *.localhost/CN=localhost, O = Dummy Certificate This is my chrome certificate invlaid screenshot: -
checkbox getlist return nothing - django
I am using checkbox in this way: <input type="checkbox"name="group1"value="0"> <input type="checkbox"name="group1"value="1"> <input type="checkbox"name="group1"value="2"> <input type="checkbox"name="group1"value="3"> in my view.py boxes = request.POST.getlist("group1") Which the boxes is an empty array. I have also tried: boxes = requset.POST.getlist("group1", []) boxes = request.POST.getlist("group1[]") boxes = request.POST("group1") <-- I have seen from other post said this would only return the value the value of last element but I am also okay as the box will only have one box clicked however, all of the above cannot successfully get the checkbox value. So I am not sure is this javascript affect the getlist: $('input[type="checkbox"]').on('change', function() { $('input[name="' + this.name + '"]').not(this).prop('checked', false); }); But I have also tried to disable the javascript, still not working -
Please help me to remove this Django APP ID type error
I'm new to Django and I'm trying to install requirements for a Django project of My teammates after cloning it. but it is not working and I can't also make migrations. whenever I try running migrations I'm getting this error (name, text, type(obj))) TypeError: app_id should be a string instead it is a <class 'NoneType'> Any help will be highly appreciated -
Django: How to Access Installed Third Party App's Model and Data
I have been using django-river(https://github.com/javrasya/django-river) application within my app (https://github.com/rupin/WorkflowEngine) I have used the Django rest framework in my application and would like to get the data from the django-river tables. The name of the table is State. My serializer is as follows from river.models import State from rest_framework import serializers class StateSerializer(serializers.Serializer): class Meta: model = State fields = ['id', 'label'] Also, my API view is as follows from rest_framework import generics from workflowengine.riverserializers.StateSerializer import StateSerializer from river.models import State class StateList(generics.ListAPIView): serializer_class = StateSerializer def get_queryset(self): return State.objects.all() Through the Admin console, I have added 11 states inside my state table, which I have checked with pgadmin. When i access the API through the browser, I get 11 empty sections in my API ( no error, just the data is missing). I cant seem to understand how the 11 data points presented in the API are empty. That it presented 11 elements, but no data, which is pretty weird. -
How to get and set the page number in django listview with pagination?
In our application, we have some Records and RecordSets and the RecordListView page shows Records of a RecordSet: class RecordListView(PaginationMixin, ListView): paginate_by = 10 def get_queryset(self): record_set_pk = self.kwargs.get('record_set') recordSet = RecordSet.objects.get(pk=record_set_pk) self.recordSet = recordSet self.queryset = recordSet.record_set.all().order_by('title') return self.queryset The problem is that 'Record' have an attribute named checked and I want to navigate to the page that the last checked record is in there! (or the first not checked record) I have found that self.kwargs.setdefault('page', desired_page_number) shows the desired page but it freezes the page and disables the navigation. So I tried to set a condition to check page argument value but self.kwargs.get('page') is always None. However I found that I can get page number from in str(self.request) but I think it's a little messy and there must be a better solution. Isn't there?! -
Rest_framework_swagger without authorization in Django
I have the following settings for REST_FRAMEWORK in my django project: REST_FRAMEWORK = { ... 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticatedOrReadOnly',), ... } I want to see all methods in rest_framework_swagger without authorization. I know that by default swagger doesn't show the methods you don't have access to. How can I override it? I have already tried to experiment with SWAGGER_SETTINGS in my settings.py file but it seems to me that is hasn't 'no authorization' option. -
I want to dynamically change the form of django according to user information
Although it is in the title, I want to change the form dynamically with django. But now I get an error. I can't deal with it. I was able to get user information, but if I filter it, it will be “cannot unpack non-iterable UPRM object”. #forms.py class RecordCreateForm(BaseModelForm): class Meta: model = URC fields = ('UPRC','URN','UET','URT',) def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(RecordCreateForm,self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' self.fields['URN'].choices = UPRM.objects.filter(user=user) #views.py class RecordCreate(CreateView): model = URC form_class = RecordCreateForm template_name = 'records/urcform.html' success_url = reverse_lazy('person:home') def get_form_kwargs(self): kwargs = super(RecordCreate, self).get_form_kwargs() # get users, note: you can access request using: self.request kwargs['user'] = self.request.user return kwargs #models class UPRM(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) URN = models.CharField( max_length=30,editable=True) def __str__(self): return self.URN class URC(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) UPRC = models.CharField(max_length=300) URN = models.ForeignKey(UPRM, on_delete=models.CASCADE) def __str__(self): return self.UPRC cannot unpack non-iterable UPRM object -
i can not work with zeep in python - missing element error
i want to make a payment gateway in django with zeep module i want to test this payment gateway in my local host i got help from the site that produce payment gateway and wrote this code views.py from django.shortcuts import render, redirect from django.http import HttpResponse from zeep import Client MERCHANT = '00' client = Client('https://www.zarinpal.com/pg/services/WebGate/wsdl') amount = 1000 description = 'تست درگاه پرداخت' CallbackURL = 'http://localhost:8000/' #whatever! i am just testing def send_request(request): result = client.service.PaymentRequest(MERCHANT, amount, description, CallbackURL) if result.Status == 100: return redirect('https://www.sandbox.zarinpal.com/pg/StartPay/' + str(result.Authority)) else: return HttpResponse('Error code: ' + str(result.Status)) def verify(request): if request.GET.get('Status') == 'OK': result = client.service.PaymentVerification(MERCHANT, request.GET['Authority'], amount) if result.Status == 100: return HttpResponse('Transaction success.\nRefID: ' + str(result.RefID)) elif result.Status == 101: return HttpResponse('Transaction submitted : ' + str(result.Status)) else: return HttpResponse('Transaction failed.\nStatus: ' + str(result.Status)) else: return HttpResponse('Transaction failed or canceled by user') then runserver but i get this error Exception Value: Missing element CallbackURL (PaymentRequest.CallbackURL) Exception Location:C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\zeep\xsd\elements\element.py in validate, line 280 -
OSMGeoAdmin: Imported OSM maps: points, lines and roads are ok, not multipolygons
Download an OSM map from geofabrik. Import it with osm2pgsql (basic commands, no fancy stuff) You will have your tables ready to use. Here's are my models (all the same fields for Line, Polygon, Point and Roads, just one is enough): class PlanetOsmLine(models.Model): class Meta: db_table = 'planet_osm_line' managed = False osm_id = models.BigIntegerField(primary_key=True) # ...tons of other field (unused)... way = GeometryField(default=None) Now, to display it in the admin interface, basic admin.ModelAdmin does the job and it work, like this for a road: Let's add the OSMGeoAdmin interface with this code: class PlanetOsmAdmin(OSMGeoAdmin): pass my_admin_site.register(PlanetOsmLine, PlanetOsmAdmin) my_admin_site.register(PlanetOsmPolygon, PlanetOsmAdmin) my_admin_site.register(PlanetOsmPoint, PlanetOsmAdmin) my_admin_site.register(PlanetOsmRoads, PlanetOsmAdmin) You'll get this, which is way nicer: OSM Admin works with everything except polygons. Here's the basic view: And when I do my_admin_site.register(PlanetOsmPolygon, PlanetOsmAdmin) then I get only this, always the same place: If the polygons are displayed properly without OSMGeoAdmin, and are not displayed properly with it. There's no error in the console log of Chrome. What am I missing?