Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Celery Monitoring BTC (Bitcoin) Addresses
im currently integrating Bitcoin payments into my app so that users can spend them after deposit but i dont get the idea how to properly monitore the addresses i previously generated To generate an new address my Celery-Task looks like this: @app.task def allocate_new_btc_address(user_pk): user = User.objects.get(pk=user_pk) new_address = subprocess.Popen("electrum createnewaddress", shell=True,stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip() try: user.acc_btc_addr = new_address user.save() logger.info("New BTC address has been allocated to a user account") except Exception as e: print(e) this returns a new unsed address a user can deposit onto and will be saved to the users acc_btc_addr Database field. So far so good. If i now want to get the balance of an address i can do something like this: subprocess.Popen("electrum getaddressbalance $user.acc_btc_addr", shell=True,stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip() which should again return something like that: electrum getaddressbalance 1ExxxLPpw18X4srexxxG3MxJYe4aXxXZnd { "confirmed": "0.00001", "unconfirmed": "0" } now im thinking about 1. How to properly parse these vaule 2. How to monitore for transactions if a user deposits 2 times to the same address? 3. What's a effective way to monitore e.g. 1.000 addresses? Thanks and kind regards -
is there any solution for authentication with vuejs and django?
I use the Django framework as backend and vue.js and webpack for the frontend. to implement authentication, send a request via ajax to django and want to keep session for next requests but can not keep session. I use the request node module for send request and use the jar to keep session but can't. in vuejs: var request = require('request'); get_jar(){ if(this.jar){ return this.jar; } this.jar = request.jar(); return this.jar; } send_ajax(url, data, method, callback){ request( { url: url, method: method, form: data, jar: this.get_jar(), }, function(err, res, body){ callback(err, res, body) }); } in django: @method_decorator(csrf_exempt, 'dispatch') class Login(View): @staticmethod def post(request): email = request.POST.get('email', None) password = request.POST.get('password', None) user = authenticate(request, username=email, password=password) if user is None: return JsonResponse({'message': 'incorrect username or password'}, status=403) else: login(request, user) return JsonResponse({'message': 'user logged in'}) a decorator for check user log in: def user_login_required(method): @wraps(method) def wrap(request, *args, **kwargs): if request.user.is_authenticated: return method(request, *args, **kwargs) else: return JsonResponse({'message': 'user not recognized'}, status=403) return wrap can somebody help me, please? -
Conditions on the Last Value of a Related Model in a Many-to-Many Relationship
As a newbie programmer I have following two models, where both models are connected to each other in a many-to-many setting. Imagine there are thousands of assignments made for hundreds of tasks, some of "Take" type, some of "Drop" time and at various times. My goal is to query the following both conditions together: Find all tasks with no assignment AND Find all tasks whose latest assignment is of "Drop" type class Tasks(models.Model): task_message = models.TextField(null=True, blank=True) task_assignment = models.ManyToManyField('Assignments',blank=True,related_name="assignments") class Assignments(models.Model): assignee = models.ForeignKey(User, on_delete=models.SET_NULL, blank=False,null=True,related_name="assigned_user") Type = ( (TAKE, 'Assigned To'), (DROP, 'Dropped From'), (FORWARD, 'Forwarded To'), ) assignment_type = models.CharField(choices=Type, default=TAKE,max_length=20) assignment_update_date = models.DateTimeField(default=timezone.now) -
Pushing notification with image attachments using PyAPNS
I am trying to attach images in iOS push notifications using PyAPNS. How can I add this attachment into the apns payload structure? We can send the notification with title, subtitle, and body. -
How to create a custom date field with Ethiopic calendar in Python/Django
I am building a django application where I need to store date information. But I am working on Ethiopian data and the default date time/calendar in python/django is gregorian. Is there a way I can create custom date time object that matches the ethiopic calendar and configure it as a default date time object. -
DJANGO , custom LIST_FILTER
I am using only the django admin , and trying to creating a custom filter, where is to filter the date of another model. My models class Avaria(models.Model): ..... class Pavimentacao(models.Model): avaria = models.ForeignKey(Avaria, related_name='AvariaObjects',on_delete=models.CASCADE) date= models.DateField(blank=True,null=True) AvariaAdmin class AvariaAdmin(admin.ModelAdmin): list_filter = ('') -
Control the name for a constraint in django
I have the problem that I need to replace a FOREIGN KEY constraint, generated by django, by a ON DELETE CASCADE constraint. What I want to do is to extend the django generated migration to implement the following with RunSQL: Drop the constraint generated by Django with DROP FOREIGN KEY Create a new constraint with ON DELETE CASCADE. To perform the first operation, I need the name of the FOREIGN KEY constraint, but this is automatically generated by django. How can I force the name of a FOREIGN KEY constraint? (not the name of the FOREIGN KEY column, which is a different thing) -
Execute query with multiline string
I try to directly access DB and render data on my webpage. Evereything works properly with one line SQL query but multiline queryies. My SQL Query consist of many joins and uses temp tables! I tried def merchant_ajax(request): data = dict() with connections['mssql'].cursor() as cursor: query_head = """ MY MULTILINE QUERY""" cursor.execute(query_head) data['data'] = cursor.fetchall() return JsonResponse(data,safe=False) My query works properly on SQl Operations Studio, but I can't realize it on django. -
Selenium with Django
I am writing a API with Django that will scrape some data using Selenium. In most cases, users will call multiple endpoints to issue different commands to the same session, based on the information coming back from the scraper. My problem is that I have no way to save the Selenium webdriver object into a Session, for instance, because it can't be pickled/converted to JSON. Any other method I've tried of saving the webdriver object in between endpoint calls provokes bizarre and inconsistent behavior from Django. For instance, I have a global webdrivers dictionary in my views.py file, and use request.session._session_key as the key and the webdriver object as the value. This often provokes key errors on subsequent calls, so something clearly isn't saving correctly. I have no idea why, but I've had all kinds of bizarre problems with state in Django that I assume is due to some kind of race condition or issue with different threads/processes. Any other suggestions on what I can do? -
Customized validation of 'Employee_Name' in my EmployeeForm class is not working
I have made a form to create Employee details. In forms.py I have made class EmployeeForm and also added a customized validation to validate 'Employee_Name' there, but the customized validation 'EmployeeNameValidate' is not working. forms.py class EmployeeForm (forms.ModelForm): Employee_Name = forms.CharField(widget=forms.TextInput(attrs{ "placeholder" : "Enter the Employee Name " } )) Employee_ID = forms.CharField(initial = '17CS') Address = forms.CharField( required = False , widget = forms.Textarea ( attrs={ "placeholder": "Enter your Address here ", "class" : "new-class-name two", "id" :"my-id-for-textarea", "rows":10, "cols":100 } ) ) Salary = forms.DecimalField(initial = 60000.24) class Meta: model = Employee fields = [ 'Employee_Name', 'Employee_ID', 'Address', 'Salary' ] #print("yaaah !!") def EmployeeNameValidate(self, *args , **kwargs): print("yaaah 22222 !!") Employee_Name = self.cleaned_data.get("Employee_Name") print(Employee_Name) if "abc" not in Employee_Name: raise forms.ValidationError ("This is not a valid Employee Name ") return Employee_Name #print("yaaah 3333333333!!") views.py def emp_create_view(request): form = EmployeeForm(request.POST or None ) if form.is_valid(): form.save() form = EmployeeForm() context={ 'form': form } return render(request,"employee/emp_create.html",context) emp_create.html {% extends "base.html" %} {% block content %} <h1> Enter the details of the Employee : </h1> <form method = 'POST'> {% csrf_token %} {{ form.as_p }} <input type='submit' value='Save' /> </form> {% endblock %} -
Search Filter Not working in pagination Django
I am search in listview using SearchForm. Even i have added pagination inside my code which is working prefectly. But the problem is that when i search and then it works but the problem is that when i go to second page of pagination then search filter get erased and no filter remains Views.py class JobListView(LoginRequiredMixin, generic.ListView): template_name = 'jobs/job.html' form_ = JobSearchForm() paginate_by = 2 context_object_name = 'jobs' def get_queryset(self, *args, **kwargs): if 'status' in self.request.GET: self.form_ = JobSearchForm(self.request.GET, instance=self.instance) jobs = Jobs.objects.none() if self.form_.is_valid(): status = self.form_.cleaned_data['status'] start_date = self.form_.cleaned_data['start_date'] end_date = self.form_.cleaned_data['end_date'] company = self.request.user.userprofile.user_company lookups = (Q(job_company=self.request.user.userprofile.user_company)) if start_date: lookups = lookups & Q(job_created_on__gte=start_date) if end_date: lookups = lookups & Q(job_created_on__lte=end_date) if status == 'Active': lookups = lookups & Q(job_status=status) if status == 'Inactive': lookups = lookups & Q(job_status=status) jobs = Jobs.objects.exclude(job_is_deleted = True).filter(lookups) else: company_name = self.request.user.userprofile.user_company jobs = Jobs.objects.exclude( job_is_deleted = True ).filter( job_company=self.request.user.userprofile.user_company ) return jobs def get_context_data(self, *args, **kwargs): context = super(JobListView, self).get_context_data(**kwargs) context["form"] = self.form_ return context Forms.py ACTIVE_CHOICES = ( ('AllStatus', 'Select Status'), ('Active', 'Active'), ('Inactive', 'Inactive'), ) class JobSearchForm(forms.Form): start_date = forms.DateField(label=False) end_date = forms.DateField(label=False) status = forms.ChoiceField(choices=ACTIVE_CHOICES, label=False, initial="") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['start_date'].widget.attrs['placeholder'] = 'Start … -
postgresql django managing many to many tables
I have an existing PostgreSQL database with a many to many relationship, it is handled through a join table as below. I'm looking to apply the ManyToMany Field type, does this bypass this join/intermediate table? How do I correctly configure it in my models.py? I'd rather keep the intermediate table. # models.py class Sample(models.Model): sample_id = models.AutoField(primary_key=True) ... class JoinSampleContainer(models.Model): id = models.AutoField(primary_key=True) container_id = models.ForeignKey(Container, db_column='container_id', on_delete = models.PROTECT) sample_id = models.ForeignKey(Sample, db_column='sample_id', on_delete = models.PROTECT) ... class Container(models.Model): container_id = models.AutoField(primary_key=True) -
Is there a way to send messages to MQTT mosquitto broker when a database change happens?
I am working on a project which is eventually going to be a website displaying device data with the option to control these devices. I am currently working on the code in python using Paho MQTT Python library. I successfully managed to send and receieve ecrypted messages via mosquitto broker. I have created a client which is a sort of monitoring client that subscribes to a wildcard topic in order to receieve all messages going through the broker and is eventually going to store them into a database. I am using django 2.1.5, mosquitto broker 1.5, working in python. The problem I am facing right now is that I can't figure out a way to send messages to the mosquitto broker as soon as a database change happens. Let's say I have a website that shows all connected devices and I want to turn one off, I'd click a button, that would change a database table, then a message has to be send to the broker to notify the device that it should switch off. I know I can make the website a client, which would then use MQTT over websockets but that is not a desirable option. I tried … -
How Django view's decide which html page to render/display?
In my View i have not mentions template_name then how django will decide which html page to render during request? Here is my views.py : from django.shortcuts import render from django.views.generic import ListView, DetailView from . models import Movie class MovieList(ListView): model = Movie # template_name = 'movie_list.html' class MovieDetail(DetailView): model = Movie #template_name = 'movie_detail.html' As shown in code i haven't mention any template_name then how django know page location? when i use url "http://localhost:8000/movies/" it display's MovieList.html -
CKEDITOR mathjax formula not show completely
I am using ckeditor with mathjax plugin to type formula. However the formula is not displayed completely. The end part of the formula is missing. I guess its width is not enough. This is html code that ckeditor generates: <span class="math-tex">\(\left[ {{{ - \pi } \over 2};\,{{3\pi } \over 2}} \right]\)</span> If I use mathjax library to display this code, it shows correctly. Only on ckeditor, it has the issue. Do you know how to solve this issue? -
What I need to build real time chat?
I'm using django rest framework to build api's for mobile app, and now I'm trying to build a real time chat. What I need is guide me to get my first step in this feature. I mean what things that I need to build a real time chat from a-z. Because I read a lot, and my collected information nested together. So any one can guide me please help me. Many thanks, -
Validate DRF response against OpenApi 3 .yml schema
I've specified Api schema in a file called apidocs.yml using OpenApi 3 specifications. Now I want to validate django-rest-framework api response against that particular .yml schema. How do I go about doing that? I've searched on google and couldn't find any libraries capable of doing that. The closest I've found was library called flex but it only support OpenApi version 2. Is there a python packaged that could validate json response from API against OpenApi 3 .yml schema file? -
URL not found when using NestedSimpleRouter and APITestCase
I am able to do the CRUD operation when i'm accessing the API through Postman and Swagger.But when i am trying to access the URL through TestCases it is showing not found error. This is happening when i am trying to access a nested-routed url in my test cases.What is the correct way to doing in Test cases. urls.py from django.conf.urls import include, url from rest_framework_nested import routers router = routers.SimpleRouter(trailing_slash=False) router.register('company', CompanyViewSet, base_name='companies') company_routers = routers.NestedSimpleRouter(router, r'company', lookup='companyrate') company_routers.register(r'rate', RateViewSet, base_name='disposal-rate') urlpatterns = [ url(r'^', include(router.urls)), url(r'^', include(company_routers.urls)), ] test.py from rest_framework.test import APITestCase from users.models import User class TestCompanyRates(APITestCase): fixtures = ['user.json', 'company.json'] data = { "company": 1, "rate": 123 } def setUp(self): self.user = User.objects.get(email='coordinator@outlook.com') self.client.force_authenticate(user=self.user) def test_rates(self): response = self.client.post('company/1/rate/', self.data) self.assertEqual(response.status_code, 201, "API should return 200 OK status") Can someone please help me out in finding the solution.I am new in APITestCases. I am using django 2.1 , python 3.6 and drf-nested-routers 0.90.URL and error is mentioned below. This is the error i am getting when tying to post the data to the URL. URL :localhost:8000/company/1/rate and Error :status_code=404, Not Found Please help me out...Thanks in advance.... -
i want to add multiple timers on different parts of my django webpage using javascript
i am creating a website in which there are various campaigns. user can set timer to this campaigns. there is a webpage in which all campaigns are listed in table. and i want to show timer of every campaign in that particular table using javascript. I have created a js function which takes timeout and starts timer but i want to show multiple timer at a time. Thank you. -
Django - Update div as plain text after I create a post using ajax
My project has a Post model. My home page has list of all post and post_create form. I create post using ajax view. Intention was to create a new post and update the home page without page refresh. Here is the code, views.py, def post_create_ajax(request): if request.is_ajax(): if request.method == 'POST': title = request.POST.get('the_post') author = request.user post = Post(title=title, author=author) print(title) post.save() return JsonResponse({'title': title}) The script, $('#postform').submit(function(event){ event.preventDefault(); console.log('Working'); create_post(); }); function create_post(){ console.log('Create Post is working'); var posttitle = $('#id_title').val(); $.ajax({ url: '/ajaxcreate/', type: "POST", data: { the_post: posttitle, csrfmiddlewaretoken: '{{ csrf_token }}', }, dataType: 'json', success: function(data){ $('#id_title').val(''); console.log(data.title); $('#post_title_content').html(data.title); }, error:function(){ console.log('Error Occoured'); alert('Error'); }, }) } This part works fine. The page new post is getting added without refresh. Here is a problem. After I submit a post, the new title that getting added are not safe. e.g. if I add <b> This is a title </b>, The new div is added with This is a title and only returns to plain text <b> This is a title </b> after I refresh the page. So my question is how to change my script so that it will update div as plain text? Images: -
How can I add search_index for RawHTMLBlock?
This FieldBlock don't have get_searchable_content property. Is it possible to search in these fields? -
Extend Django-admin change_form.html, checkbox to filter form queryset
How could I add a custom checkbox in a models change_form.html to apply a filter to a forms base_field queryset. I know I can do this when I retrieve the form like so def get_form(self, request, obj=None, **kwargs): form = super(Model, self).get_form(request, obj, **kwargs) form.base_fields['XXX'].queryset = OtherModel.objects.filter(condition=True).order_by(field) return form But I was hoping to make this a dynamic filter on the change screen. Does anybody have a tutorial or example code to help please. I expect some javascript will be required. Thanks -
This field is required error but field is in the form
So I have a form which I initiallize with request.POST, but, even if thje form has the correct field it isnt valid, what am I missing? def some_view(self, request): form = SomeForm(request.POST or None) if form.is_valid(): (Pdb) form.data <QueryDict: {u'csv_file': [u'some_csv_file.csv'], u'csrfmiddlewaretoken': [u'csrftoken']}> (Pdb) form.is_valid() False (Pdb) form.errors {'csv_file': [u'This field is required.']} -
django 1.9 how to keep session after change password through ajax request
I have a function to update user data by ajax def ajax_update(request): if request.method == 'POST': update_form = forms.UserUpdateForm(request.POST, instance=request.user) if update_form.is_valid(): update_form.save() response['status'] = 'success' return JsonResponse(response) and a UserUpdateForm class UserUpdateForm(forms.ModelForm): class Meta: model = User exclude = ['password'] def save(self, commit=True): instance = super(UserUpdateForm, self).save(commit=False) instance.set_password(self.cleaned_data['password_1']) instance.save() return instance After set_password executed and save the instance, It returned 'success' message. However, When I reload the page Its session was expired Is there a way to keep session after change password by ajax? -
Success Message in Django Rest Framework
I want to send success message status result_count. When returing response. Similar to bellow JSON response { "status":true, "result_count":5, "message":"Timesheet Retrieved Successfully.", "result": [ { "user_id": "40", "user_name": "Derek Hedrick", "data": [ { "timesheet_id": "2", "job_id": "11", "job_code": "rfyxlv", "clock_in": "2018-09-07T03:00", "clock_out": "2018-09-07T15:00" "note": "This is test note", "type": { "regular":"7", "overtime":"2" } }, But i am getting reponse like this [ { "id": 1, "job_group": 1, "job_name": "RAJJUUU", "job_number": "hjhasfd", "job_description": "Json", "job_start_date": "2018-03-29", "job_start_time": "14:20:00", "job_end_date": "2018-03-29", "job_end_time": "14:20:00", "job_status": "Active", "job_created_on": "2019-01-28T08:32:47.327096Z" } ] How can i add custom messages. This is my ListAPIView class JobsListAPIView(generics.ListAPIView): serializer_class = JobListSerialzer # pagination_class = ListLimitOffsetPagination permission_classes = [UserIsAuthenticated] def get_queryset(self, *args, **kwargs): # print('self.request.auth', self.request.auth.application.user.userprofile.user_company.id) qs = Jobs.objects.exclude(job_is_deleted = True).filter( job_company = self.request.auth.application.company ) start_date = self.request.query_params.get('start_date', None) end_date = self.request.query_params.get('end_date', None) job_name = self.request.query_params.get('job_name', None) if start_date is not None: qs=qs.filter(job_start_date=start_date) if end_date is not None: qs=qs.filter(job_end_date=end_date) if job_name is not None: qs=qs.filter(job_name=job_name) return qs Serializer.py class JobListSerialzer(serializers.ModelSerializer): class Meta: model = Jobs fields = [ 'id', 'job_group', 'job_name', 'job_number', 'job_description', 'job_start_date', 'job_start_time', 'job_end_date', 'job_end_time', 'job_status', 'job_created_on', ]