Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
refresh component state every time it is rendered react
I have an API running and I am trying to fetch that to get some information about some products. I am using react router to route the products and using that to fetch the API. However, when I try clicking on a different product the information from the previous product remains no matter what I do. Here is my fetch: componentWillMount(){ let id = this.props.params.id + 3; let url = 'http://localhost:8000/api/item/' + id + '/'; return fetch(url) .then(results => results.json()) .then(results => this.setState({'items': results})) .catch(() => console.log(this.state.items)); and where I call the fill the information render() { return ( <div className="itemPageWrapper"> <div className="itemImgWrapper" /> <div className="itemInfoWrapper"> <Link className="backLink" to="/"> <span className="small"> <svg fill="#000000" height="13" viewBox="0 0 18 15" width="13" xmlns="http://www.w3.org/2000/svg"> <path d="M7 10l5 5 5-5z"/> <path d="M0 0h24v24H0z" fill="none"/> </svg> </span>All Items </Link> <h3 className="itemName">{this.state.items[Number(this.state.id)].name}</h3> <p className="itemCost frm">{this.state.items[Number(this.state.id)].price}</p> <p className="description"> {this.state.items[Number(this.state.id)].description} </p> <p className="seller frm">By <span>{this.state.items[Number(this.state.id)].brand}</span></p> <button className="reqTradeBtn normalBtn">Order</button> </div> </div> I receive an error saying TypeError: Cannot read property 'name' of undefined if I change anything. I am using a +2 because my API starts at 3. How would I make this work for all products -
Using Luigi within Django
I developed a pipeline with Luigi framework. Now I would like to trigger it, within a webapp (Django), by pressing a button. However, when I run the pipeline from the webapp, I get the following error: signal.signal(signal.SIGUSR1, self.handle_interrupt) ValueError: signal only works in main thread" Here is my code: def run_pipeline(): p = Pipeline() exec p def index_view(request): if request.GET.get('btnRun'): t = threading.Thread(target=run_pipeline) t.setDaemon(True) t.start() return render(request, 'index.html') -
The empty path didn't match any of these. (Python3, Django, URLS)
Sorry for my english, im from RU Im learning Python3, im install python and django on my webserver. But i have a problem with urls, im reading any topic but i dont finding answer for my question (so sorry for my eng). sctructure: expnk.ru HelloDjango (1) HelloDjango (2) setting.py .......... urls.py cat ... any apps app "cat" im create from ssh command: python3 manage.py startapp cat next im going to HelloDjango (2) and edit file setting.py, for INSTALLED_APPS im add 'cat' after im going to file HelloDjango (2) -> urls.py, im add on this file next string: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^cat/', include('cat.urls')), url(r'^admin/', admin.site.urls), url(r'^blog/', include('blog.urls')), url(r'^test/', include('test.urls')), ] after im going to: cat -> urls.py and add on this file: from django.conf.urls import url, include from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] last, im edit file views, code from this file: from django.shortcuts import render from django.http import HttpResponse def index(response): return HttpResponse("Hello world!") # Create your views here. I created the cat application similar to the blog application, as a result: the blog is running, cat is not. Please, help -
Celery use Django Result Backend on Remote tasks
I have a Django application that use Celery to create async tasks. Some of these tasks live within the Django project and other live on a remote worker with its own code base. I currently use the django-celery-results package to store the results of task calls within the Django database so that I can easily query the status of calls using the Django ORM. This works fine when I call my "local" tasks, but it does not seem to work as well when I call remote tasks. For example: app.send_task("django.foo") # Return status SUCCESS and store result in DB app.send_task("remote.bar") # Stuck in PENDING and never create result in DB By reading the Celery Docs I found out that tasks can be stuck in PENDING if the client and worker doesn't use the same CELERY_RESULT_BACKEND setting. In this case I can't use the django-db backend on my remote worker, since it's not a Django application. So in this case... How do I store my results when doing remote calls in this manner? Note that in the case of remote.bar, I confirm that the remote worker receives the message and executes the method. Its just that my client (Django App) doesn't … -
Django-FCM returns OK but I didn't receive the notification
I made an backend with Django for an Android Application. I have to send some notifications to the device and for that, i installed Djando-fcm (https://django-fcm.readthedocs.io/en/stable/quickstart.html). My problem is when i test "python manage.py fcm_messenger --device_id=3 --msg='my'" The application returns Succesfull, but the notification doesn't recieved. [OK] device #3 (Test): ([u'fZwT3TGUMig:APA91bGa1QVfKzKjrKUwCFQKKRk5cjiKfli52-nKtWf6T1EYc9rxg9LRje1YOw6OHt-M6ho4n9ps4JZkRqZ3vmhBfH3k9WE88c80tqHbgck4lLiBpBGOW7kMLJxFVKrSDhwv5kKUWXIb'], {u'failure': 0, u'canonical_ids': 0, u'success': 1, u'multicast_id': 8479349601166653607L, u'results': [{u'message_id': u'0:1548084391335752%150287e038eb0007'}]}) My requirements.txt is (Python 2.7): Django==1.11.10 djangorestframework==3.7.7 mysqlclient==1.3.12 pytz==2018.3 virtualenv==15.1.0 amqp==2.4.0 billiard==3.5.0.5 celery==4.2.1 certifi==2018.8.24 chardet==3.0.4 Django==1.11.10 django-fcm==0.1.1 djangorestframework==3.7.7 idna==2.7 kombu==4.2.2.post1 mysqlclient==1.3.13 pytz==2018.3 requests==2.19.1 urllib3==1.23 vine==1.2.0 -
Is there any way to run channels on azure app service?
I have currently run websocket locally with django channel (tutorial chat) I would like to submit the project on azure app service, I have enabled websockets in the control panel. however this does not work, once in my browser on the site I cannot connect to the socket either in http or https. I changed my webconfig also by putting <webSocket enabled="false" /> in order not to use the IIS module. What would you recommend me? isn't it because of the wsgi handler? -
How do I write a Django ORM query with a relation that isn't defined in the model?
I'm using Django and Python 3.7. I have the following two models in my models.py file ... class Article(models.Model): created_on = models.DateTimeField(default=datetime.now) ... class ArticleStat(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, ) elapsed_time_in_seconds = models.IntegerField(default=0, null=False) I would like to write a Django ORM query where I select articles have a stat that's at least 5 minutes (300 seconds) old. However, I don't know how to reference the ArticleStat object from the Article object. Unsurprisingly, this Article.objects.filter(articlestat.elapsed_time_in_seconds.lte==300) produces a NameError: name 'articlestat' is not defined error. -
How to get the result from async function in python using Celery + Redis
I am new to task queue. When i open the shell and execute the function add.delay(3,4) from the function in the shell to perform the task. I get : <AsyncResult: 30db3528-5b0f-4e74-bf47-51956a1f83e9>. How do I get a result from this function and what should i do to schedule the result to be executed 5 second later? celery.py from future import absolute_import, unicode_literals import os from celery import Celery app = Celery('RedisQueue') app.autodiscover_tasks() @app.task def add(a, b): return a + b init.py from future import absolute_import, unicode_literals all = ['celery_app'] settings.py CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' -
How to loop through extended user model fields in Django template?
I have extended Django's user model with a Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') date_of_birth = models.DateField() address = models.CharField(max_length=300) postcode = models.CharField(max_length=15) Then, I pass this data into a template via this view: def profile(request): args = {'user': request.user} return render(request, 'users/profile.html', args) Then I can access each field of the Profile model individually in the template with: <p>Your DOB is: {{ user.profile.date_of_birth }}</p> However, I want to use a for loop to say: {%for field in Profile model %} <p>{{field name}} = {{field value}} {% endfor %} But I've tried a lot of different things, none of them work, e.g. {% for field in user.profile.all %} <p>{{ field }}</p> {% endfor %} (This compiles but is blank when the template is ran) -
Django - code after Object creation is not executed
My code is: if part_one is None: print("########### PART ONE") part_one = Company.objects.create( name=name, owner=request.user, source=source ) print("########### PART TWO") PartTwo.objects.create( first_names=name.split(" ")[0], last_names=" ".join(name.split(" ")[1:]), source=source, party=party ) The problem I am facing is that the second print statement or any code thereafter is not executed anymore. Is this something django specific? I do not seem to find any reason why the function gets aborted after creating Part One -
Run Django with gunicorn, Celery and Celery Beat
I have a docker-compose file like this: backend: image: ${API_IMAGE} env_file: - .env depends_on: - db volumes: - ./data/server/static/:/usr/src/api/static - ./data/server/uploads/:/usr/src/api/uploads restart: always frontend: image: ${FRONTEND_IMAGE} env_file: - .env ports: - "80:80" volumes: - ./data/server/logs:/usr/src/web/logs - ./configs/nginx:/etc/nginx/conf.d - ./data/server/static/:/usr/src/app/static - ./data/server/uploads/:/usr/src/app/uploads restart: always celery: image: ${API_IMAGE} env_file: - .env working_dir: /usr/src/api/ environment: DJANGO_SETTINGS_MODULE: 'core.settings' depends_on: - redis command: /bin/sh -c "celery -E -A core worker -l info" beat: image: ${API_IMAGE} env_file: - .env working_dir: /usr/src/api/ environment: DJANGO_SETTINGS_MODULE: 'core.settings' depends_on: - celery command: /bin/sh -c "celery -A core beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler" Everything is accessed through the frontend container which is a Nginx application using proxy to send request to others containers. The backend is running with the CMD in a bash file with: /usr/local/bin/gunicorn --access-logfile - -w 4 core.wsgi:application -b 0.0.0.0:80 & Everything is fine, and running. But if I access the admin site, and try to use Celery Beat to create a Periodic Task, show me this error: Traceback (most recent call last): backend_1 | File "/usr/local/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ backend_1 | return obj.__dict__[self.__name__] backend_1 | KeyError: '_modules' backend_1 | backend_1 | During handling of the above exception, another exception occurred: ... File "/usr/local/lib/python3.6/site-packages/celery/app/base.py", line 684, in … -
How to test a view using the request object
I need to make tests to see if my view is working properly. However, I did not find how to use the request object in the test file. My view function is: def track_view(request): user_email, user_order = request.session['email'], request.session['order'] if request.method == 'POST': client_id = request.META.get('HTTP_HOST').split(':8000')[0] payload = "{ \n\"description\": \"Rastreio de pedido\", \n\"subject\": \"Rastreamento " + user_order + ' ' + user_email + "\", \n\"email\": \"" + user_email + "\", \n\"priority\": " + str( priority['low']) + ", \n\"status\": " + str(status['closed']) + ", \n\"group_id\": " + str(group[ 'Logística']) + ", \n\"type\": \"Rastrear Pedido\", \n\"product_id\": " + str(client[client_id]) + "}" headers = { 'Content-Type': "application/json", 'Cache-Control': "no-cache" } response = requests.request("POST", url, data=payload, headers=headers, auth=('XXX', 'X')) print(response.text) context = {'email_variable': user_email, 'order_variable': user_order} return redirect('atendimento:final_view') logo_image = 'client_logo/' + request.META.get('HTTP_HOST').split(':8000')[0] + '.png' context = {'logo_image': logo_image, 'user_email': request.POST.get('email'), 'user_order': request.session['order']} return render(request, 'atendimento/track_page.html', context) How can I make that work to test different inputs to that view? -
How to update nested serializers with file field
I have 2 models: Profile and Image. Profile field "logo" related to Image with models.ForeignKey() construction. I want to update my Profile record with update request (Patch with JSON payload). How can I do that? I've tried to send this JSON { "name": "TestName", "company": "myCompany", "phone": "33222111", "website": "site.com" } And it's OK, record have updated. But! In Image model I have models.ImageField(). How I should deal with this field through another serializer? Then I've tried to send this JSON (122 id of existed Image record in DB) REQUEST: { "logo": 122 } ANSWER: { "logo": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got int." ] } } OK, so, think I should send object of exist record REQUEST: { "logo": { "id": 122, "uuid": "bf9ba033-208f-47e0-86e5-93c44e05a616", "created": "2018-12-20T12:54:57.178910Z", "original_name": "hello.png", "filetype": "png", "file": "http://localhost/upload/img/0a9lg1apnebb.png", "owner": 1 } } ANSWER: { "logo": { "file": [ "The submitted data was not a file. Check the encoding type on the form." ] } } Here my two models and serializers class Image(models.Model): id = models.AutoField(primary_key=True) uuid = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) created = models.DateTimeField(auto_now_add = True) original_name = models.CharField(max_length = 256, default=None) filetype = models.CharField(max_length = 10, default=None) file = models.ImageField(upload_to=update_img_filename, … -
ModelForm with ModelMultipleChoiceField how to group choices based on their parent model?
What I want to achieve is this: Category1 Choice1 Choice2 Choice3 Category2 Choice1 Choice2 etc. I use a custom ModelMultipleChoiceField. The problem is in my template I can not present them in their categories. Instead they all are generated under eachother. my forms.py: class CustomAmenitiesSelectMultiple(CheckboxSelectMultiple): """ CheckboxSelectMultiple Parent: https://docs.djangoproject.com/en/2.1/_modules/django/forms/widgets/#CheckboxSelectMultiple checkbox_select.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/checkbox_select.html multiple_input.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/multiple_input.html checkbox_option.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/checkbox_option.html input_option.html: https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/input_option.html """ template_name = "forms/widgets/custom_checkbox_select.html" option_template_name = 'forms/widgets/custom_checkbox_option.html' class AmenitiesForm(ModelForm): class Meta: model = Venue fields = ('choices',) choices = forms.ModelMultipleChoiceField(Amenity.objects.all(), widget=CustomAmenitiesSelectMultiple,) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if kwargs.get('instance'): initial = kwargs.setdefault('initial', {}) initial['choices'] = [c.pk for c in kwargs['instance'].amenity_set.all()] forms.ModelForm.__init__(self, *args, **kwargs) def save(self, commit=True): instance = forms.ModelForm.save(self) instance.amenity_set.clear() instance.amenity_set.add(*self.cleaned_data['choices']) return instance custom_checkbox_option.html: {% if widget.wrap_label %} <label{% if widget.attrs.id %} for="{{ widget.attrs.id }}"{% endif %}>{% endif %}{% include "django/forms/widgets/input.html" %}{% if widget.wrap_label %} {{ widget.label }}</label> {% endif %} custom_checkbox_select.html {% with id=widget.attrs.id %} <div class="inline field"> <div {% if id %} id="{{ id }}" {% endif %}{% if widget.attrs.class %} class="{{ widget.attrs.class }}" {% endif %}> {% for group, options, index in widget.optgroups %}{% if group %} <div> {{ group }} <div> {% if id %} id="{{ id }}_{{ index }}" {% endif %}>{% endif %}{% for option in options … -
Can't save image to django ImageField
im currently facing a problem i really dont understand. i have several models in my models.py beside a post model also a category_request model. Anyways, i'm able to save the ImageField for the post model but not for the category_requests model. i diff the two a lot of times but i m not able to see the issue :( the fields simply does not get saved at the database. models.py class CategoryRequests(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=20, verbose_name="Title") description = models.TextField(max_length=175, null=True, blank=True) cover = fields.ImageField( blank=True, null=True, upload_to=get_file_path_user_uploads, validators=[default_image_size, default_image_file_extension], dependencies=[FileDependency(processor=ImageProcessor(format='JPEG',quality=99,scale={'max_width': 700, 'max_height': 700}))]) published_date = models.DateField(auto_now_add=True, null=True) status = StatusField() STATUS = Choices('Waiting', 'Rejected', 'Accepted') up_vote = models.IntegerField(default=0) down_vote = models.IntegerField(default=0) def publish(self): self.published_date = timezone.now() self.save() class Meta: verbose_name = "CategoryRequest" verbose_name_plural = "CategoryRequests" ordering = ['title'] def __str__(self): return self.title As already mentioned, the working post model: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=25) content = models.TextField(max_length=5000) tag = models.CharField(max_length=50, blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True) postattachment = fields.FileField( blank=True, null=True, upload_to=get_file_path_user_uploads, validators=[file_extension_postattachment, file_size_postattachment] ) postcover = fields.ImageField( upload_to=get_file_path_user_uploads, validators=[default_image_size, default_image_file_extension], dependencies=[FileDependency(processor=ImageProcessor(format='JPEG',quality=99,scale={'max_width': 700, 'max_height': 700}))]) published_date = models.DateField(auto_now_add=True, null=True) def publish(self): self.published_date = timezone.now() self.save() class Meta: verbose_name = "Post" verbose_name_plural … -
django upgrade from 2.0.2 to 2.1.5
I upgraded django 2.0.2 to 2.1.5 Because 2.0.2 has maybe distinct() and count() error. After I upgrade django with pip install -U django, when I python manage.py runserver there was it: You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin. Run 'python manage.py migrate' to apply them. So I type that: python manage.py migrate Then, this comes: Operations to perform: Apply all migrations: admin, auth, contenttypes, ipn, sessions, sites Running migrations: Applying admin.0003_logentry_add_action_flag_choices... OK If being on production, Is it okay to do that? What does that means? -
Django 2 namespace and app_name
I am having a difficult time understanding the connection between app_name and namespace. consider the project level urls.py from django.urls import path, include urlpatterns = [ path('blog/', include('blog.urls', namespace='blog')), ] consider the app level (blog) urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.post_list, name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), ] if I comment out app_name, I get the following. 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. If I rename app_name to some arbitrary string, I don't get an error. app_name = 'x' I've read the documentation but its still not clicking. Can someone tell me how/why app_name and namespace are connected and why are they allowed to have different string values? -
Django 2.1 Model Observers
Does DJango 2.1 have any support for observers on models? I've looked into https://github.com/lambdalisue/django-observer, but it appears to only support up to 1.6. My goal is that everytime a model is updated, I want to fire and command that executes other functions. -
Django generics.ListAPIView accepting POST method
I have a Django view which extends generics.ListAPIView. It works fine with get requests, however since the char limits of the URL, now I need to send the request via POST. It is the same request, the only thing I need to change is the method to POST. My current code is pretty simple: class MyClass(generics.ListAPIView): serializer_class = MySerializer paginate_by = 1 def get_queryset(self): queryset = SomeClass.objects.all() # do some filtering How could I add POST support to this class? -
Default Value 0 (Zero Number) in Django Model
I want input default value whenever the entry is Null inserted. Always it is inputing null value in my MySQL Database. So i Changed my Model but defuault entry 0 is not inserting class TimesheetHours(models.Model): timesheet = models.ForeignKey(TimesheetEntry, on_delete=models.CASCADE,related_name='timesheet_hours') timesheet_hour_regular = models.IntegerField(default=0,blank=True, null=True) Views.py - Saving Form form_hour = TimesheetHours( timesheet=form_timesheet, timesheet_hour_regular = form.cleaned_data['timesheet_hour_regular'], timesheet_hour_overtime = form.cleaned_data['timesheet_hour_overtime'], timesheet_hour_doubletime = form.cleaned_data['timesheet_hour_doubletime'], timesheet_hour_travel = form.cleaned_data['timesheet_hour_travel'], timesheet_hour_admin = form.cleaned_data['timesheet_hour_admin'], timesheet_hour_other = form.cleaned_data['timesheet_hour_other'], timesheet_hour_created_by=self.request.user, timesheet_hour_updated_by=self.request.user ) form_hour.save() -
Django and Elasticbeanstalk: Is there a way to see Django's error messages on production as turning on debug?
I'm really having trouble with solving this problem. Django and Elasticbeanstalk There is a thing that doesn't work on eb even though the part works on local) and I'd like to see error messages as I do on local. I checked error log on elastic beanstalk but there's no error. Is there a way to do it safely? Here is the recent error log. [Mon Jan 21 13:55:23.231664 2019] [http2:warn] [pid 12378] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm will just not do. This is an advisory warning. Your server will continue to work, but the HTTP/2 protocol will be inactive. [Mon Jan 21 13:55:23.231673 2019] [http2:warn] [pid 12378] AH02951: mod_ssl does not seem to be enabled [Mon Jan 21 13:55:23.232196 2019] [lbmethod_heartbeat:notice] [pid 12378] AH02282: No slotmem from mod_heartmonitor [Mon Jan 21 13:55:23.232251 2019] [:warn] [pid 12378] mod_wsgi: Compiled for Python/3.6.2. [Mon Jan 21 13:55:23.232255 2019] [:warn] [pid 12378] mod_wsgi: Runtime using Python/3.6.5. [Mon Jan 21 13:55:23.234475 2019] [mpm_prefork:notice] [pid 12378] AH00163: Apache/2.4.34 (Amazon) mod_wsgi/3.5 Python/3.6.5 configured -- resuming normal operations [Mon Jan 21 … -
Django- UnboundLocalError: local variable 'forms' referenced before assignment
I'm trying to make a form get information from the user regarding feedback. Here's my code: I'm a little new to Django, can you please help me? Below is my forms.py file:- from django import forms class FeedBackForm(forms.Form): name=forms.CharField() rollno=forms.IntegerField() email=forms.EmailField() feedback=forms.CharField(widget=forms.Textarea) Below is my views.py file:- from django.shortcuts import render from . import forms # Create your views here. def feedback_view(request): form=forms.FeedBackForm() if request.method=='POST': forms=forms.FeedBackForm(request.post) if form.is_valid(): print('Form Validation Success and printing Feedback info') print('Student Name:',form.cleaned_data['name']) print('Student Roll No:',form.cleaned_data['rollno']) print('Student Mail ID:',form.cleaned_data['email']) print('Student Feedback:',form.cleaned_data['feedback']) return render(request,'testapp/feedback.html',{'form':form}) Its throwing below error UnboundLocalError at /feedback/ local variable 'forms' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/feedback/ Django Version: 2.1.4 Exception Type: UnboundLocalError Exception Value: local variable 'forms' referenced before assignment Exception Location: F:\Django\feedbackproject\testapp\views.py in feedback_view, line 5 Python Executable: C:\Users\Prashant\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.0 Python Path: ['F:\\Django\\feedbackproject', 'C:\\Users\\Prashant\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\Prashant\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\Prashant\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\Prashant\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\Prashant\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages'] Server time: Mon, 21 Jan 2019 13:54:35 +0000 -
How to call templates outside app folder?
How can I call the header.html? This is my folder structure. I'm having a "TemplateSyntaxError at /". - Project Name - App - Home - Templates //will contain all the views - home.html - views..py - Templates //will contain all the scripts,styles - header.html Here is my code: Home/templates/home.html {% extends '../../templates/header.html' %} {% block content %} <body> </body> {% endblock content %} -
Razorpay payment button connection in django
Hey I'm trying to make donation web app in django I have never work in gateway application. views.py def payment_page(request): form = PaymentForm(request.POST or None) donation = request.POST.get('donation') try: donation = int(donation) * 100 # Note 1 Rs == 100 ps donation = str(donation) except TypeError: donation = 100 # If delete this you will TypeError Razorpay money should be greater than 1 ps return render(request, 'mysite/payment_page.html', {'form':form, 'donation':donation}) What I done in try block? 1 rs is equal to 100ps so I multiple it with 100. If I don't use the try it give me typeError payment_page.html <div class="container"> <div class="jumbotron"> <form method="post">{% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-danger">Donate</button> </form> </div> </div> <form action="/purchase" method="POST"> <!-- Note that the amount is in paise = 50 INR --> <script src="https://checkout.razorpay.com/v1/checkout.js" data-key="rzp_test_VKwzQnRYkTmxEW" data-amount="{{ donation }}" data-buttontext="Pay" data-name="Merchant Name" data-description="Purchase Description" data-image="" data-prefill.email="{{ email }}" data-theme.color="blue" ></script> <input type="hidden" value="Hidden Element" name="hidden"> </form> How it working right now I enter name, donation amount, email in form click donate the amount it save in database and after that I press pay it display the amount, but I want only one button which can do the both work at the same … -
How to test clean_<fieldname> method?
I try to write a test for my clean_ method. Here is the code for my test def test_clean_restraints(self): form = NewTaskForm(dict(restraints="90 20 <>")) form.clean_restraints() At this step I receive an error: Error Traceback (most recent call last): File "/home/user/django_projects/my_webservice/tasks/tests/test_forms.py", line 12, in test_clean_restraints form.clean_restraints() File "/home/user/django_projects/my_webservice/tasks/forms.py", line 22, in clean_restraints if self.cleaned_data.get('restraints') == '': AttributeError: 'NewTaskForm' object has no attribute 'cleaned_data' NewTaskForm looks like this: class NewTaskForm(ModelForm): class Meta: model = Task restraints = forms.CharField() region = forms.CharField() interactions = forms.CharField() def clean_restraints(self): if self.cleaned_data.get('restraints') == '': return self.cleaned_data.get('restraints') data = self.cleaned_data.get('restraints').strip().split('\n') regexp = re.compile(r'^(\d+)[\t ]+(\d+)[ \t]+([><]{2})?$') cleaned_data = [] for i, line in enumerate(data): match = regexp.match(line) if not match: raise forms.ValidationError(f"Error in restraints in line {i + 1}") else: rst_1, rst_2, loop_type = match.groups() rst_1 = int(rst_1) rst_2 = int(rst_2) cleaned_data.append((rst_1, rst_2, loop_type)) return cleaned_data I'm using Django 2.1, python 3.7.1, PyCharm 2018.3.3 Professional I tried to run it under debugger in PyCharm but things goes crazy. I receive different error message. It looks like debugger stopped after full form validation ignoring breakpoints. I have no idea what is going on.