Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use get_object() properly?
I have a tricky problem with UserPassesTestMixin. I've added print so I can see what is going on. The problem here is that post.author, is somehow attached to first record from database. So when I'm logged in as a user who posted a first comment, I have access to every other post, I can edit them since self.request.user == post.author is always fulfilled, but it shouldn't. I thought this part post.author will show the author of the post I'm currently trying to access. Any ideas? class DiscussionView(LoginRequiredMixin, CreateView): model = Discussion template_name = 'tripplanner/discussion.html' fields = ['text'] ... def form_valid(self, form): form.instance.author = self.request.user print(form.instance.author) print(self.request.user) form.instance.group = self.trip return super().form_valid(form) class DiscussionCommentUpdate(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Discussion template_name = 'tripplanner/comment_update.html' fields = ["text"] ... def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() print(self.request.user) print(post) print(post.author) if self.request.user == post.author: return True return False -
Play a live stream output video of a machine learning model in the browser in Raspberry Pi in Django Web App
I have a machine learning model which is provided with the url of a camera and after clicking the button the machine learning model get connected and starts analysing the video received from the camera. This happens but in another window which gets open by default when the model starts running. I have a Django web app, where the output data of the model is displayed on the website. I want that whenever the url is submitted, the live video coming from that camera should open in my browser and not in another window. Please guide me as how to do this. This is the input text-area and button: <input type="text" name="videourl" id="id_videourl"/> <input type="button" class="btn btn-secondary btn-lg" id="id_submit" name="submit" value="Start" /> This sends an ajax call and the machine learning model connects and starts working. Kindly help me out here. -
Django Apache - Virtualhost with HTTPS not starting
I just want to create a VirtualHost with Apache over https. I browsed half the internet but nothing could help me. I'm using OpenSSL for the certificate and my OS is Windows. Listen 443 <VirtualHost *:443> ServerName www.foo.com ServerAlias foo.com SSLEngine On SSLCertificateFile C:/Users/Myzel394/Documents/foo/certificate/aula_com.csr SSLCertificateKeyFile C:/Users/Myzel394/Documents/foo/certificate/aula_com.key DocumentRoot C:/Users/Myzel394/Documents/foo WSGIScriptAlias / C:/Users/Myzel394/Documents/foo/foo/wsgi.py <Directory C:/Users/Myzel394/Documents/foo/foo> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> -
path('<username>') causing all urls to map to incorrect view
I have a Django app called chat and the root urls.py looks like this path('messages/', include('chat.urls')), However the url below, in the chat app urls.py is causing problems re_path(r"^(?P<username>[\w.@+-]+)", login_required(chat_views.ThreadView.as_view()), name='thread'), What is happening is that instead of throwing a 404 does not exist error when I go to a made up url such as localhost/messages/blahblah/02 It instead throws NOT NULL constraint failed: chat_thread.second_id Because it is assuming blahblah/02 is a username and is mapping it to the ThreadView which fails to get the thread object from 2 users. So essentially, any other url pattern I try to create in the chat app doesn't route properly. (Example I tried creating a NotificationListView but couldn't access it due to routing messages/notifications to ThreadView) How can I stop this from happening? -
Permission denied with django migrations in docker
I'm using docker compose with django - postgres - rabbitmq All is going good even django container is up and running to the point I want to makemigrations it stops with django-celery-beat Migrations for 'django_celery_beat': django_1 | /usr/local/lib/python2.7/site-packages/django_celery_beat/migrations/0005_auto_20190512_1531.py django_1 | - Alter field event on solarschedule django_1 | Traceback (most recent call last): django_1 | File "/app/manage.py", line 10, in <module> django_1 | execute_from_command_line(sys.argv) django_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line django_1 | utility.execute() django_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute django_1 | self.fetch_command(subcommand).run_from_argv(self.argv) django_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv django_1 | self.execute(*args, **cmd_options) django_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute django_1 | output = self.handle(*args, **options) django_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 193, in handle django_1 | self.write_migration_files(changes) django_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 232, in write_migration_files django_1 | with io.open(writer.path, "w", encoding='utf-8') as fh: django_1 | IOError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/site-packages/django_celery_beat/migrations/0005_auto_20190512_1531.py so I tried to add sudo user to the python-2.7 alpine but actually I failed to run this command with sudo permission So what should I do, should I run the image using virtualenv inside docker or is there any tweak to fix this one -
Dokku Compilation Error - django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'
I've been attempting to setup my built-up Django Instance as a Database Server. Had chosen DigitalOcean as my platform and had read that Dokku is a useful PaaS system that will enable better scalability for this API I'm trying to deploy. I have been at this problem for the last 3-4 days straight and really had gone through every potential means of solution I could have found online. Being more of a front-end developer, I'm pretty bad at this backend installation matter. At first I thought that Dokku was sort of a Git-push function where I will push from localhost -> Dokku -> Git -> Deploy. Digging deep, I setup Public-Private keys for Dokku to authorize a Git push to Github. Ultimately, after finally giving up on that route, I did realised I was in the wrong and roughly the way Dokku should work is localhost -> Git push -> Dokku -> Deploy. Been at this for the last 15-18 hrs of development. The flow seemed to work, where I didn't really need to do much installations on the DigitalOcean droplet. However, the biggest issue I am facing is with this My current install is as so: DigitalOcean Droplet 1-click … -
How to update a tuple which is in database from edit form in Django?
I am trying to modify a tuple in the database via a formular and I have not been able to do so since. I would like a sample code that works. -
how to print only values from database by avoiding row name and so ( in Django)
am using Django and database is mysql , when am printing id from row its printing { id: 45 } , but I only need result 45...someone can help? itemList = todoitem.objects.filter(content__in=wordlist).values("id") -
How to solve django_easy_pdf don't support unicode text?
My django version is 2.0, python 3. Does anyone know how to solve the problem of django_easy_pdf do not support unicode text? thank you in advance. -
Pass to signals.py form field
I have a code, which helps me to initiate Profile creation, while User is registered. I'd like to add one of the fields to the signals, and as a result in the sex parameter I'd like to add value from my form, which is sex. Any ideas? signals.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance, sex="Male") forms.py class UserRegisterForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, label=_(u'First name')) last_name = forms.CharField(max_length=30, required=False, label=_(u'Last name')) email = forms.EmailField(label=_(u'Email')) sex = forms.ChoiceField(choices=GENDER, label=_(u'Gender')) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'sex'] -
Having an error in django's raw SQL syntax
I got error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'radians(151.20711)) + sin(radians(-33.86714)) * sin(radians(ads_suburb.latitude)' at line 1" when I ran below code. query = '''SELECT id, longitude, latitude, (6378 * acos(cos(radians(-33.86714)) * cos(radians(latitude)) * cos(radians(longitude) – radians(151.20711)) + sin(radians(-33.86714)) * sin(radians(latitude)))) AS distance FROM ads_suburb HAVING distance < 10 ORDER BY distance;''' surrounded_suburbs = Suburb.objects.raw(query) for suburb in surrounded_suburbs: print(suburb.id) Where do I need to fix? -
how to display notification in django admin
Here i have a code for the Newsletter.And with this code i want to give notification like 1 new email added inside the model name in admin page if new email is added from the newsletter form.how can i do this ?can anyone help me to edit this code?I got this exception with this code Exception Type: TypeError Exception Value: Object of type Newsletter is not JSON serializable models.py class Newsletter(models.Model): email = models.EmailField() date_joined = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email forms.py class NewsletterForm(forms.ModelForm): # def clean_email(self): # email = self.cleaned_data['email'] # if User.objects.filter(email=email).exists(): # raise ValidationError('You Already Joined') # return email class Meta: model = Newsletter fields = '__all__' views.py def newsletter(request): initial = {'email': [], 'count': 0} session = request.session.get('data', initial) if request.method == "POST": form = NewsletterForm(request.POST or None) if form.is_valid(): email = form.save(commit=False) session['email'].append(email) session['count'] += 1 request.session['data'] = session email.save() messages.success(request, 'Thank You for Joining.') return redirect('/') index.html {% for model in app.models %} <tr class="model-{{ model.object_name|lower }}"> {% if model.admin_url %} <th scope="row"><a href="{{ model.admin_url }}">{{ model.name }} {% if model.name == 'Newsletter' %} <b style="color:red;">{{request.session.data.count}} New Email </b> {% endif %}</a></th> {% else %} <th scope="row">{{ model.name }}</th> {% endif %} {% if … -
Django: Filter objects by a range of two integers
I have a search form with id, price_from, price_to and drive_from, driven_too, but since price and driven are the same logic I am only focusing in one of these, since price_from and price_to are not in the model, it gives me an error because this parameter does not exist, therefore it can not compare anything. How can i search in the car objects for an object which price is within this range (price_from - price_to), should i modify my model? # model class Car(models.Model): id = models.CharField(max_length=255) number = models.CharField(max_length=255) price = models.IntegerField() # view def search(request): if 'search_filter' in request.GET: search_params = request.GET.dict() search_params.pop("search_filter") price_from = search_params['price_from'] price_to = search_params['price_to'] q_list = [Q(("{}__icontains".format(param), search_params[param])) for param in search_params if search_params[param] is not None] my_query = Car.objects.filter(reduce(operator.and_, q_list)) cars = [{ 'id': x.id, 'driven': x.driven, 'price': x.price, } for x in my_query ] return JsonResponse({'data': cars}) context = {'cars': Car.objects.all().order_by('price')} return render(request, 'cars/car_index.html', context) -
User and Profile models filled in one form
I use build-in User model, which is extended with sex field. I've written some code, so I can see extra field during registration: forms.py class UserRegisterForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, label=_(u'First name')) last_name = forms.CharField(max_length=30, required=False, label=_(u'Last name')) email = forms.EmailField(label=_(u'Email')) sex = forms.ChoiceField(choices=GENDER, label=_(u'Gender')) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'sex'] What I'm struggling with, that after sending form, other fields are saved in db, except for sex. Any ideas? views.py class RegisterUser(SuccessMessageMixin, FormView): form_class = UserRegisterForm template_name = 'accounts/register.html' success_url = reverse_lazy('login') success_message = 'Your account has been created! You are now able to log in' def form_valid(self, form): form.instance.author = self.request.user form.save() return super(RegisterUser, self).form_valid(form) signals.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() models.py GENDER = ( ('Male', 'male'), ('Female', 'female') ) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') sex = models.CharField(choices=GENDER, max_length=6) def __str__(self): return "{} Profile".format(self.user.username) def save(self, *args, **kwargs): sex = getattr(self, 'sex') if sex == "Male" or sex == "male": self.image = "profile_man.png" else: self.image = "profile_woman.png" super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, … -
pass request.user into form with ModelMultipleChoiceField , Django
I want to pass request.user or request.user.pk from class based view to the ModelForm in order to filter query set with request.user.pk . I have a following view: class ArticleResurrectionView(MessageLoginRequiredMixin, FormView): model = Article form_class = ArticleResurrectionForm template_name = "articles/resurrection.html" success_url = reverse_lazy("articles:articles_main") redirect_message = "You have to be logged in to recover articles " def get_form_kwargs(self): kwargs = FormView.get_form_kwargs(self) kwargs["author_id"] = self.request.user.pk return kwargs def get_form_kwargs(self): should pass self.request.user.pk as a kwargs["author_id"] to form’s init Then I have following form for this view: class ArticleResurrectionForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.author_id = kwargs.pop("author_id", None) forms.ModelForm.__init__(self, *args, **kwargs) title = forms.ModelMultipleChoiceField(label="Deleted articles", help_text="Please select the article to recover", queryset=Article.default.filter(show=False, author=???) ) # I can not use self.author_id here Target is to use self.author_id from init in the title to filter queryset in a such way to show entries only made by current user. In another words I need to pass self.author_id in the queryset in title. Perhaps it is possible to do it by something like that: def __init__(self, *args, **kwargs): self.author_id = kwargs.pop("author_id", None) forms.ModelForm.__init__(self, *args, **kwargs) self.fields[“title].queryset = ??? Anyway, if you know how to get request.user in the queryset – I would be happy to get your solution … -
Can`t run existing Django project
I downloaded python 3.7 and django framework. There is an existing project I want to run and execute. I've added python interpreter, there wasn't any errors and then I tried to run it and... as ypu can see there are a lot of errors. I don't know the reason and a way to solve that problem Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Python\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Python\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Python\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Python\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "C:\Python\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Python\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Python\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Python\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'social_django' Traceback (most recent call last): File "C:/Users/skantorp/Documents/Univer/Task02/SSPLS/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Python\lib\site-packages\django\core\management\__init__.py", line … -
can I insert image into database using django?
I am currently developing a website that can help user carry out a survey. For the results section I want to throw charts and bar graphs. I'm working in Django. Please help me manage the charts using database (mysql). I already am familier with ImageField in models but my tables are dynamic. Also you can suggest a better way if there is any to throw pie charts and bar graphs whenever user requests. Thanks in Advance -
How can I add autocomplete to django_filters?
I have implemented a few filters using django_filters and that works fine. But I want to show search suggestions when user type on the filters. How can I do this? I tried to add django_autocomplete_light but that is not working or I could not configure it properly. Right now, I have the following code for filters: class ProductFilter(django_filters.FilterSet): product_name = django_filters.CharFilter(lookup_expr='icontains', label='Product Name', ) product_price = django_filters.NumberFilter() product_price__gt = django_filters.NumberFilter(field_name='product_price', lookup_expr='gt', label='Minimum Price') product_price__lt = django_filters.NumberFilter(field_name='product_price', lookup_expr='lt', label='Maximum price') product_category = django_filters.CharFilter(lookup_expr='icontains', label='Category') vendor_name = django_filters.CharFilter(lookup_expr='icontains', label='Retailer Name') class Meta: model = Product fields = ['product_name', 'product_price', 'vendor_name', 'product_category'] class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['product_name', 'product_price', 'vendor_name', 'product_category'] I am using widget_tweaks for forms. Now, What can I do to make these fields to enable autocomplete? Please help. -
Why would my server spawn two threads in response to one Http POST?
So... who likes detective work, pouring over a log record??? Here's one for the sleuths amongst us! One of our users states they encountered an error page while sitting a quiz on our site. Below I attach some text from our server logs related to the moment they reported. I think the third column (8 or 9) refers to the thread on the server. So at 07:36:31, the user is having an HTML reponse being prepared for them via a series of function calls in response to a POST from the user (answering previous quiz question). But after a second POST from the user at 07:36:44 for some reason the server seems to have spawned two threads running in parallel in response to what I presume is a single POST request. You can see the error at the end and the reason for it. For the first thread (8), an entry was saved to the database. When the second thread reaches that point just milliseconds later, we get an integrity error because a record with that key already exists (thanks to thread 8). I've never had this problem before. Any ideas as to WHY suddenly our server decided to suddenly … -
Inlineformset_Factory save data much as extras
I need to save 2 model in one form. And relation is foreign key relation. I used inlineformset_factory for this. And I wanna "add new item" for foreign key form. if inlineformset factory: extras=1 When I entry just a value for foreign key; Its okey. When I entry 3 or more values for foreign key; Only save last one. if inlineformset_factory: extras 3 When I entry 3 values for foreign key; Its okey. but when I try entry 4 or more, only save 3 item. my form class TestForm(ModelForm): class Meta: model = ciranta exclude = () TestFormSet = inlineformset_factory(parentModel, childModel, form=CirantaForm, extra=1) my view class TestCreate(CreateView): model = parentModel fields = ['var1','var2','var3'] success_url = reverse_lazy('home') def get_context_data(self, **kwargs): data = super(TestCreate, self).get_context_data(**kwargs) if self.request.POST: data['childModel'] = TestFormSet(self.request.POST) else: data['childModel'] = TestFormSet() return data def form_valid(self, form): context = self.get_context_data() childModel = context['childModel'] with transaction.atomic(): self.object = form.save() if chilModel.is_valid(): childModel.instance = self.object childModel.save() return super(TestCreate, self).form_valid(form) my template: <table class="table"> <br> {{ childModel.management_form }} {% for form in childModel.forms %} {% if forloop.first %} <thead class="thead-light"> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1 row2 … -
Perform query against three tables in Django
I have three tables I am trying to join. table: TSUH id scanBegin FKToUser table: User (django user.auth table) table: T id FKToUser I'm wondering how I can match all the records between these in django. In typical psuedo SQL I'd do JOIN User.id=TSUH.FKToUser AND JOIN User.id=T.FKToUser I saw with django I can perform a .select_related() - https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.select_related I just am unsure how I can put this all together for use in a django view for my use case. Can anyone help? Thank you. -
How do I serve a django project with NGNIX
I a django test site on a guest vm on my local system that I want to serve up with NGINX so that I can later enable ssl connection to the site. This is the current directory tree of my django project: sgoodman@ubuntu19:~$ tree . └── insta ├── db.sqlite3 ├── insta_project │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── Pipfile ├── Pipfile.lock └── posts ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ └── __init__.py ├── models.py ├── tests.py └── views.py I'm trying to follow along with this tutorial. https://linuxconfig.org/how-to-setup-the-nginx-web-server-on-ubuntu-18-04-bionic-beaver-linux I have the following sites in the sites-enabled directory: sgoodman@ubuntu19:~$ ls -l /etc/nginx/sites-enabled/ total 0 lrwxrwxrwx 1 root root 34 May 12 12:22 default -> /etc/nginx/sites-available/default lrwxrwxrwx 1 root root 32 May 12 12:30 insta -> /etc/nginx/sites-available/insta This is what is in the /etc/nginx/sites-available/insta file. sgoodman@ubuntu19:~$ cat /etc/nginx/sites-available/insta server { listen 80; root /home/sgoodman/insta; index index.html; server_name 192.168.236.149; } I'm currently getting a 403 Forbidden when attempting to access htt://192.168.236.149 How do I configure nginx to serve up the django project? Thank you. -
Django! How to add a custom admin system in a website?
I am a beginner of django. I made a project. This is a online shop. Here, the builtin system of admin is nice. And I want to keep it for administration of my site(like add product, add staff, edit product details. Now what I want-- I want to add a another admin system for the user. They will sign up with some details (like email, name, password, date of birth etc). They will be able to login with email and password to buy a product. But they can not enter administration panel. They will be separated. Also they will have cart to store their order info. Now, I tried hard to do Somthing like this. But I am getting confused with what I should do or avoid. I didn't get a helpfull thing in internet for me. So, I just cleared my project and starting again from the very beginning. Now how can I make like a separated admin system in a app(my case: account) for users? -
TypeError: $(...).dropzone is not a function
i'm triying to use dropzone in my django app, I followed many examples but none of them worked for me can you please help me Js code : <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/min/dropzone.min.css" rel="stylesheet" type="text/css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/min/dropzone.min.js" type="text/javascript"></script> <script type="text/javascript"> Dropzone.autoDiscover = false; $(document).ready(function(){ $('#myDropzone').dropzone({ url: "{% url 'dashboard/import' %}", addRemoveLinks: true, success: function (file, response) { console.log("Successfully uploaded :"); }, error: function (file, response) { file.previewElement.classList.add("dz-error"); } }); }); </script> HTML code : <form action="{% url 'dashboard/import' %}" class="dropzone" drop-zone> {% csrf_token %} </form> I've got an TypeError: $(...).dropzone is not a function -
Can't hide comment using ajax after creating it using websockets
I'm trying to delete a comment that i made it using websockets by using ajax and everything works fine and successfully the comment has been deleted but when i try to hide it nothing happens code : if(newComment.action === 'create'){ console.log(newComment.action) $(".review-box").append('<div id=comment_test'+newComment.comment_id+'>'+'<small>' + newComment.author + '</small><br>' + '<p>' + newComment.comment_text + '</p>'+'<a href="#" data-id='+newComment.comment_id+' class="dele">delete</a>'+'<br><hr></div>') $('.dele').on('click', function(e){ e.preventDefault(); var comment_id = $(this).attr('data-id') data = { comment_id : comment_id, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), } $.ajax({ type : "POST", url : "{% url 'delete_comment' %}", dataType:'json', data:data, success: function(data) { console.log(data.ok) console.log('comment_test'+comment_id) document.getElementById('comment_test'+comment_id).innerHTML = '' }, error:function(e){ console.log(e); } }); }) }