Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i create download link using django?
I'm using my own project using django. I'm trying to download file using django. I finished upload file to using django. but i don't know how to create file download link in django. example) test.java , and my domain is example.com, port is 9001 and media folder is /media i just want to down https://example.com:9001/media/test.java just like this. I google all method but there's no clue.. here is my code. view.py -> upload part @csrf_exempt def index(request): return render(request, 'useraccount/index.html', {}) @csrf_exempt def file_list(request): return render(request, 'useraccount/list.html', {}) @csrf_exempt def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('file_list') else: form = UploadFileForm() return render(request, 'useraccount/upload.html', {'form': form}) upload.html <html> <head><title>Upload Test</title></head> <body> <form action="upload/" method="post" enctype="multipart/form-data"> File: <input type="file" name="file" id="id_file" /> <input type="submit" value="UPLOAD" /> </form> </body> </html> upload.html {% extends 'useraccount/index.html' %} {% block content %} <h2>Upload file</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type="submit">Upload file</button> </form> {% endblock %} list.html {% extends 'useraccount/index.html' %} {% block content %} <h2>The image has been uploaded!!</h2> {% endblock %} forms.py from django import forms from .models import UploadFileModel class UploadFileForm(forms.ModelForm): class Meta: model = UploadFileModel fields = {'title', 'file'} url.py … -
I deployed my django web application to heroku and got "Application Error" message
I successfully deployed my django web application to heroku but got Application Error message. But, the web application works properly in local server. Error Message Here is my application log: 2020-08-03T06:34:59.207955+00:00 app[web.1]: bash: gunicorn: command not found 2020-08-03T06:34:59.254715+00:00 heroku[web.1]: Process exited with status 127 2020-08-03T06:34:59.295780+00:00 heroku[web.1]: State changed from starting to crashed 2020-08-03T06:35:01.995197+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=itnewspaper.herokuapp.com request_id=9164669e-7de2-4e24-9a16-ca1e49f8f052 fwd="160.202.144.210" dyno= connect= service= status=503 bytes= protocol=https 2020-08-03T06:35:03.180446+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=itnewspaper.herokuapp.com request_id=7c59fcc0-54ca-4fe8-9e6f-68fc94ccd7af fwd="160.202.144.210" dyno= connect= service= status=503 bytes= protocol=https 2020-08-03T06:48:57.624143+00:00 heroku[web.1]: State changed from crashed to starting 2020-08-03T06:49:02.606322+00:00 heroku[web.1]: Starting process with command `gunicorn newspaper_project.wsgi --logfile-file -` 2020-08-03T06:49:04.795025+00:00 app[web.1]: bash: gunicorn: command not found 2020-08-03T06:49:04.849585+00:00 heroku[web.1]: Process exited with status 127 2020-08-03T06:49:04.891541+00:00 heroku[web.1]: State changed from starting to crashed 2020-08-03T07:14:00.163016+00:00 heroku[web.1]: State changed from crashed to starting 2020-08-03T07:14:04.805352+00:00 heroku[web.1]: Starting process with command `gunicorn newspaper_project.wsgi --logfile-file -` 2020-08-03T07:14:06.747596+00:00 heroku[web.1]: Process exited with status 127 2020-08-03T07:14:06.783177+00:00 heroku[web.1]: State changed from starting to crashed 2020-08-03T07:14:06.690452+00:00 app[web.1]: bash: gunicorn: command not found Disconnected from log stream. There may be events happening that you do not see here! Attempting to reconnect... Connection to log stream failed. Please try again later. The steps i followed to deploy: pipenv … -
Django static files using s3
I am having problems using an s3 bucket for my sites static files. Currently using django-storages and boto3. In my setting.py I have: AWS_ACCESS_KEY_ID = env("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = env("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = env("AWS_STORAGE_BUCKET_NAME") AWS_S3_FILE_OVERWITE = False AWS_DEFAULT_ACL = None AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Running collectstatic sends static files to the s3 bucket successfully, but the static urls in my templates do not update. I am using apache2 and have not changed the .conf file, do I need to? Any help would be gratefully recieved -
Django 'PdfFileWriter' object has no attribute 'get' - Creating PDFs in Django
I'm trying to generate PDFs in my Django web app using Reportlab & PyPDF2. The goal is to create a canvas with some product information & then layover that canvas on top of an existing PDF template to "fill" the template. I tested my code in Jupyter, It works fine, however, I need some help to use that code in a Django view. The following code is working in Jupyter. from PyPDF2 import PdfFileWriter, PdfFileReader import io from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter packet = io.BytesIO() # create a new PDF with Reportlab can = canvas.Canvas(packet, pagesize=letter) can.drawString(493, 724, " ".join('2009')) # hardcoded for testing purposes(will later use a form allowing the user to enter details) can.save() packet.seek(0) new_pdf = PdfFileReader(packet) # read your existing PDF existing_pdf = PdfFileReader(open('path to my existing PDF template here - template_file.pdf', "rb")) output = PdfFileWriter() # add the "watermark" (which is the new pdf) on the existing page page = existing_pdf.getPage(1) ######## select 0 to get first page, and 1 to get second page page.mergePage(new_pdf.getPage(0)) output.addPage(page) # finally, write "output" to a real file outputStream = open("destination.pdf", "wb") output.write(outputStream) outputStream.close() in order to use it in django, I created a view class … -
Django - size of ArrayField based on a field value of a related model
I have 2 models: Report and STO with a one-to-many relationship between them, so a STO can have many related reports. STO model class STO(TerminableWithTerminableRelatedModel): name = models.CharField(_('name'), unique=True, blank=False, max_length=255) description = models.TextField(_('description'), blank=True, null=True) answer_no = models.PositiveSmallIntegerField(_('number of answers'), default=5) # that's the value I'm interested in result_note = models.TextField(_('STO result note'), blank=True, null=True) Report model class Report(models.Model): @property def answer_no(self): return STO.objects.get(id=self.STO).answer_no date = models.DateField(_('date'), blank=False, null=False) STO = models.ForeignKey(STO, on_delete=models.CASCADE, related_name='reports') answers = ArrayField(AnswerField(), size=answer_no, blank=False, null=False) # here comes the problem As you can see, each Report has an array of AnswerField (AnswerField is a custom field, I've omitted it because it's out of the scope of this question). The size of this array should be specified on the related STO class, on the answer_no field. I made this decision because this value is equals for each report of a given STO, so inserting that in each single report would lead to data duplication. I've tried to achieve this using a property, but Django complaints that he can't serialize properties when doing migration: ValueError: Cannot serialize: <property object at 0x7faf02161ea0> There are some values Django cannot serialize into migration files. -
How to save form with relationship in django?
I have models with relationship as :- class Address(models.Model): street = models.CharField(max_length=100) post_box = models.PositiveIntegerField() def __str__(self): return self.street class Employee(models.Model): name = models.CharField(max_length=100) age = models.PositiveIntegerField() address = models.ForeignKey(Address, on_delete=models.CASCADE) def __str__(self): return self.name and the form is :- class EmployeeForm(forms.ModelForm): address = forms.ModelChoiceField(Address.objects.all()) class Meta: model = Employee fields = "__all__" def save(self, commit=True, *args, **kwargs): print('saving employee') post_box = kwargs['post_box'] street = kwargs['street'] address = Address.objects.create(street=street, post_box=post_box) employee = Employee.objects.create(address=address, name=kwargs['name'], age=kwargs['age']) return employee and the html form is :- <form method="post" action="{% url 'employee' %}"> {% csrf_token %} <div class="form-group"> <label for="exampleInputEmail1">Name</label> <input type="text" name="name" class="form-control" id="name" aria-describedby="emailHelp"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <label for="age">Age</label> <input type="number" name="age" class="form-control" id="age"> </div> <div class="form-group"> <label for="street">Street</label> <input type="text" name="street" class="form-control" id="street"> </div> <div class="form-group"> <label for="post_box">Post Box</label> <input type="text" name="post_box" class="form-control" id="age"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> The view would look like this: - class EmployeeView(View): def get(self, request): form = EmployeeForm() return render(request, 'employee.html', context={'form': form}) def post(self, request): data = request.POST form = EmployeeForm(data=data) if form.is_valid(): form.save() messages.success(request, 'A new Employee Created') return render(request, 'employee.html') else: return render(request, 'employee.html', context={'form':form}) This simply would not save … -
Run Django on Docker with Daphne and Gunicorn
At the moment I am trying to run a project in Docker where I need to implement websockets to my productive Django Server, so I decided to use Daphne. For now I used Gunicorn and Nginx along with Postgres as Database. My first thought was now to use Supervisor to run Gunicorn and Daphne on the same server: Container: Django + Gunicorn + Daphne Container: Nginx Container: Postgres But a Docker Best Practice is to run every process on an own container. So my thought now is to run Daphne and Gunicorn on different Containers, so Gunicorn serves the Website-Data and Daphne takes over the Socket-Things. Like: Container: Django + Gunicorn Container: Django + Daphne Container: Nginx Container: Postgres But will this work? What about the Database? Are two servers able to edit the same tables? What about the sessions and data, how to sync data between the two servers? Overall, are there any Best Practices for using Django with Daphne and Gunicorn the same time on Docker? Thanks in advance for your help! -
Detecting dev env vs. prod env Elastic Beanstalk
I have a Django app and two Elastic Beanstalks envs: dev and prod. I want to make some kind of if statement in my Django app to detect which env I am deploying to (or running locally) and use different settings accordingly. How can I do this? Thanks!! -
Python Script to test out multiple variants of email addresses
I am new to programming and Python and I am testing out an idea for emails. I want to see if I can create a Python script that will allow me to do 3 things. Allow the user to Input a name and an email url. Insert multiple variants of email name possibilities. Send out a test email to all the variants and return of one of them worked. For number 2, there would be an already set list of the most common variations such as(John.Smith, John-Smith, etc..) I have figured out how to send out emails but I am having trouble with 1 and 2. I’m not sure if a simple “for loop” will work be how to set the parameters. Thanks for your help. It’s a stupid project but I’m hoping it will help me see it a little differently -
django line 265, in to_representation return value.pk AttributeError: 'str' object has no attribute 'pk'
i want to post a request to create many instance to relate a new instance, but when one of many instance's format are not right,i want to tell client what's is happend, but it didn't return errors message, i want to know why serializer.py class MenuInfoSerializer(serializers.ModelSerializer): class Meta: model = MenuInfo exclude = ['id'] class MenuSerializer(serializers.ModelSerializer): info_list = MenuInfoSerializer(source='infos', many=True, read_only=True) class Meta: model = Menu fields = '__all__' models.py class MenuInfo(models.Model): bid_code = models.ForeignKey(Menu, related_name='infos', on_delete=models.CASCADE) service_type = models.CharField(max_length=32, default='', help_text='服务器型号') vendor = models.CharField(max_length=32, blank=False, help_text='厂商') power_dissipation = models.CharField(max_length=32, default='', help_text='满负荷功耗') weight = models.CharField(max_length=32, default='', help_text='重量') frame_size = models.CharField(max_length=32, default='', help_text='机框尺寸') price_3year = models.CharField(max_length=32, default='', help_text='三年含税单价') price_4year = models.CharField(max_length=32, default='', help_text='四年含税单价') price_5year = models.CharField(max_length=32, default='', help_text='五年含税单价') tax_rate = models.CharField(max_length=32, default='', help_text='含税率') class Meta: db_table = 'tbl_menu_info' class Menu(models.Model): bid_code = models.CharField(primary_key=True, max_length=64, unique=True) menu_code = models.CharField(max_length=64, unique=True) config_type = models.CharField(max_length=64, unique=True) one_bid = models.CharField(choices=SUPPLIER, max_length=32, db_column='bid1', blank=True, default='') two_bid = models.CharField(choices=SUPPLIER, max_length=32, db_column='bid2', blank=True, default='') one_two_ratio = models.FloatField(db_column='12_ratio', blank=True, default=-1) price = models.FloatField(blank=True, default=-1) class Meta: db_table = 'tbl_menu' views.py class MenuList(generics.ListAPIView): queryset = Menu.objects.all() serializer_class = MenuSerializer name = 'menu-list' ordering_fields = ('-pk',) def post(self, request, *args, **kwargs): with transaction.atomic(): save_id = transaction.savepoint() menu = request.data serializer = … -
How to send data to particular listening channel on client side using Django channels, when data is posted through REST?
Here is the scenario. I have an django channels app, which also consist of restapi framework (DRF) with just one view, which expects a POST call, with data. Once I get the data on that POST endpoint I wish to notify all or particular client connected via websocket (html websocket) So, creating an endpoint was the easiest one, and that has been achieved, and then using async_to_sync(channel_name)({}) (an example) is not being listened by the frontend client. Any working example of this please? -
Django Gunicorn different type of timeout
I serve a Django app with Gunicorn (using Heroku) and Sentry for monitoring. I regularly receive 2 different types of timeout error on Sentry: SystemExit 1 in gunicorn/workers/base.py in handle_abort at line 201 WORKER TIMEOUT (pid:12345) at the Gunicorn level For the second one, It produces H13 errors in Heroku which according to the docs means: This error is thrown when a process in your web dyno accepts a connection but then closes the socket without writing anything to it. One example where this might happen is when a Unicorn web server is configured with a timeout shorter than 30s and a request has not been processed by a worker before the timeout happens. In this case, Unicorn closes the connection before any data is written, resulting in an H13. which is clear enough. However for the System Exit 1, I read that it was a timeout in a similar ticket but I am not sure exactly what is the difference. -
Aborted connection 3 to db: 'default_schema' user: 'root' host: 'X.X.X.X' (Got an error reading communication packets)
I am running Django in a docker container and also I have MYSQL container running as well when I try to make a GET request I get the following from the logs. Aborted connection 3 to db: 'default_schema' user: 'root' host: 'X.X.0.X' (Got an error reading communication packets) How do i fix it? -
Django3 :Unable to link html page in django
I've created new app as register and when trying to link in html its not redirecting page after link click Project's settings.py: INSTALLED_APPS = [ 'questions.apps.QuestionsConfig', 'register.apps.RegisterConfig', # registered new app 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', ] Project's urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('questions.urls')), path('register/', include('register.urls')) #Linked apps urls.py ] Register app's views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from .forms import RegisterForm # Create your views here. def register(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect("/") else: form = RegisterForm() return render(request,'register.html',{'form':form}) def test(request): return render(request,'test.html',{'form':form}) Register app's urls.py: from django.urls import path from . import views urlpatterns = [ path('register', views.register, name='register'), ] When I use http://127.0.0.1:8000/register/register in browser's url then it;s working fine. output in browser: But when I use href tag in html to render register.html page, I am getting error. when tried: <a href="#link" class="btn btn-info" href="register/register">Register</a> I'm not getting anything and in browser url it shows as http://127.0.0.1:8000/#link when used : <a href="#link" class="btn btn-info" href="{% url 'register/register' %}">Register</a> getting error as: NoReverseMatch at / Reverse for 'register/register' not found. 'register/register' is not a valid view function or pattern name. -
interacting with an external django project from within another python (non-django) project
I created a database with Django and want to use it in another python project. I need the django models but I want a python non-django project and not want to include all the models again. So how to use models from an external django project in a python project/script? -
Paginations doesn't work in elasticsearch-dsl
I implement elastic search in latest version following this Link and all parameter like search, filter and ... works fine except page and page_size in pagination; For example When I add ?page=2 to my requesting url, it returns first 10 record! What is the problem? (I read another topics and all of them was relating to working with elastic search API not url) Thank You! -
how to change USERNAME_FIELD in Django 3.0.8. without creating a custom user?
i know same Question has already been asked and tried that solution by putting User.USERNAME_FIELD = 'email' in init.py file but it gives error raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
dynamically submit form when values change python
I am new to html and Django and trying to make my forms dynamically auto-submit whenever the user changes their inputs, essentially removing the 'Submit' button. My form has 3 inputs, (all floats) which will go through a 'some_function()' for a calculation. But to save the user time, I would like it dynamic. Hence, no 'submit'. HTML: <div class="container"> <h3>Calculator</h3> <form method="post" > {% csrf_token %} {{ form_c.as_p }} <button type="submit">Submit</button> # <- I would like to remove this </form> </div> My View is below if needed: def post(self, request): form_c = CalculatorForm(request.POST, prefix='form_c') try: if form_c.is_valid(): post = form_c.cleaned_data val1 = float(post.get('val1')) val2 = float(post.get('val2')) val3 = float(post.get('val3')) numbers = some_function(val1, val2, val3) except: pass args = { 'form_c': form_c, 'form_cols': numbers, } return render(request, self.template, args) -
How to override default http connection timeout while running development server of Django 3.0.3?
I am running Django development server and I want to change the default http connection timeout. As per this stackoverflow link, django github repo issue link and reddit link, I should pass --http_timeout argument while running the development server. But when I try to do that I am getting error I am using Django 3.0.3 version. Is there any way to override the default http connection timeout? -
Django cms IsADirectoryError
I'm upgrading python2.7 to python3.7 and Django from 1.8 to 1.11, here I'm using djangocms package. everything works fine in python2.7 and Django 1.8, but after upgrading, I'm getting an issue in one of its pages. Using django-cms==3.6.0 and its supporting packages. And here is the console log, 2020-08-03 01:33:32,065 [ERROR] exception/handle_uncaught_exception(): Internal Server Error: /schedule-appointment/ Traceback (most recent call last): File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/django/core/handlers/base.py", line 215, in _get_response response = response.render() File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/django/template/response.py", line 107, in render self.content = self.rendered_content File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/django/template/response.py", line 84, in rendered_content content = template.render(context, self._request) File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/django/template/backends/django.py", line 66, in render return self.template.render(context) File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/django/template/base.py", line 207, in render return self._render(context) File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/django/template/loader_tags.py", line 177, in render return compiled_parent._render(context) File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/home/local/TAG/ajaykumarr/.virtualenvs/medi37/lib/python3.7/site-packages/classytags/core.py", line 146, in render return self.render_tag(context, **kwargs) … -
While hosting in heroku ,after deployment i am getting Application Error: Missing required flag: » -a, --app APP app to run command against
While running heroku logs --tail i got, Error: Missing required flag: » -a, --app APP app to run command against Then i saw my logs for the failure i got, Why i am getting Failed to find attribute 'application' in 'django'. My deployment was successfull when i pushed my code to heroku master and it was deployed but i am getting this error.I added requirements.txt and ProcFile correctly.Its working perfectly in local host. Please help me in solving this!!! -
Django programming error relation does not exist despite model being created
I renamed some of my models and tried to apply the migrations, but Django didn't detect that they were renamed. Therefore I deleted the content of manage.py, flushed the db and then ran manage.py makemigrations and manage.py migrate. Now I get the following error when I try to access one of my models via admin console or via any queries: ProgrammingError at /admin/restapi/appuser/ relation "restapi_appuser" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "restapi_appuser" When I ran manage.py makemigrations the output included (truncated): Migrations for 'restapi': restapi/migrations/0001_initial.py - Create model AppUser I tried to run python3 manage.py sqlmigrate restapi 0001_initial with the following output (truncated): BEGIN; -- -- Create model AppUser -- CREATE TABLE "restapi_appuser" ("id" serial NOT NULL PRIMARY KEY, "username" varchar(30) NOT NULL UNIQUE, "email" varchar(50) NOT NULL UNIQUE, "password" varchar(50) NOT NULL, "join_date" timestamp with time zone NOT NULL); It seems to me like the model should be in the database, but I am wondering why I am getting this error -
HttpResponseRedirect would't redirect edit page to another page that displays edit result by Django
It only returns the edit page without being redirected to the the result page (title.html by entry function). Any help would be appreciated. My code is as below: views.py class EntryForm(forms.Form): title = forms.CharField() content = forms.CharField(widget=forms.Textarea()) def entry(request, title): entries = util.list_entries() rand = random.choice(entries) try: mark_content = util.get_entry(title) output = markdown2.markdown(mark_content) return render(request, "encyclopedia/title.html", { "content": output, "random": rand, "title": title }) except TypeError: return render(request, "encyclopedia/error.html", { "random": rand }) def edit(request, title): if request.method == "post": form = EntryForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] util.save_entry(title, content) return HttpResponseRedirect(reverse('title', args=(title,))) else: data = { 'title': title, 'content': util.get_entry(title) } original_form = EntryForm(initial=data) entries = util.list_entries() rand = random.choice(entries) return render(request, "encyclopedia/edit.html", { "form": original_form, "random": rand, "title": title }) urls.py urlpatterns = [ path("", views.index, name="index"), path("create", views.create, name="create"), path("edit/<str:title>", views.edit, name="edit"), path("search", views.search, name="search"), path("<str:title>", views.entry, name="entry") ] It for editing an existing page, saving the changes and being redirected to the title page for result display. But it seems it stuck in the edit page. Please help. Thanks. -
In django, use django-dbbackup and django-crontab to backup automatically
I'm use django-bdbackup and django-storage backup my db into aws s3, fortunately it work. In the next step, I want to it backup automatically, but it's not lucky this time. I add two things in SETTINGS: INSTALLED_APPS = [ ... ... ... 'django_crontab', ... ... ... ] and CRONJOBS = [ ('*/1 * * * *', 'django.core.management.call_command', ['dbbackup'],{'-o':'2020-07/dbbackup_20200801.7z'}) ] It's not work.There are nothing in my s3 bucket, and no message appeared. Can anyone tell me what I wrong or something I miss? -
Call Django Class based view function with Django-Q's async_task
I can't call async_task on a Django class based view function. Considering following case, where I have a DRF view: class Greeting(generics.GenericAPIView) def greet(self, name): print("Hello: ") sleep(5) print(name) def post(self, request, *args, **kwargs): # enqueue the task async_task("how.to.call.self.greet", "world") return Response( {"message": "you should see this right away"}, status=status.HTTP_200_OK ) When trying to call async_task on a Django class based view function, following errors occur: async_task(self.greeting) returns an cannot pickle '_io.BufferedReader' object error async_task("self.greet") returns an No module named 'self' error I have no issues when putting the greet function outside de class. That is, however, a "solution" a would like to avoid.