Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiprocessing within redis queue
I'm working with a django application hosted on heroku with redistogo addon:nano pack. I'm using rq, to execute tasks in the background - the tasks are initiated by online users. I've a constraint on increasing number of connections, limited resources I'm afraid. I'm currently having 2 connections for 2 diffrent types of task. For instance, lets say if 4 users initiate same type of task, I would like to have my main worker create child processes dynamicaly to handle it. Is there a way to achieve required multiprocessing and concurrency? I tried with multiprocessing module, initially without introducing Lock(); but that exposes and overwrites user passed data to the initiating function, with the previous request data. After applying locks, it restricts second user to initiate the requests by returning a server error - 500 github link #1: Looks like the team is working on the PR; not yet released though! github link #2: This post helps to explain creating more workers at runtime. This solution however also overrides the data. The new request is again processed with the previous requests data. Let me know if you need to see some code. I'll try to post a minimal reproducible snippet. Any … -
how to print png chart from google charteditor?
From the official documentation of Google charts, It provides the following syntac for getting the imageURI() for a specific chart type: var my_div = document.getElementById('chart_div'); var chart = new google.visualization.ChartType(chart_div); google.visualization.events.addListener(my_chart, 'ready', function () { var imgUri = chart.getImageURI(); //perform print function }); However I am using Google's chart editor method, and I am unable to retrieve the imageURI for the chart selected. chartEditor = new google.visualization.ChartEditor(); google.visualization.events.addListener(wrapper, 'ready', function () { var imgUri = chartEditor.getChart().getImageURI(); //throws error: getChart().getImageURI() not a function of chartEditor }); I am particularly new to the usage of Chart editor function. -
How to implement facebook like notifications using django 1.9 as backend and angular 7.2 as frontend?
I have a web application which uses DRF as backend and angular 7.2 as frontend. The version of Django we are currently using is 1.9. I want to implement facebook like notifications so what would be the best way to implement. Is sending request from FE on certain endpoint after few seconds good option? I also went through channels library for WebSockets but seems like it doesn't support Django 1.9. -
How to create monthly shift scheduler in Django
I would like to kindly ask you for some idea how to approach a shift scheduling app in Django. I need to push forward. In the picture, there is described how I want the app to look. https://imgur.com/a/d8XxdKX I have models Shift, Department, Employee and Scheduler (Date, shift_fk, department_fk, employee_fk) How would you approach it? I just need an idea how to connect all those models and display shifts in correct columns and rows Thank you very much Filip -
Django - Create An Endpoint Which Accepts Multiple Values For A Search Field
Full Disclosure: I am a front-end Javascript developer helping with resolving this internal issue we have: Our Django backend is currently serving an endpoint with the following signature: *.api/search_field/?category=abc&category=bcd&category=def What I want to know is that is there a way to simplify the above endpoint to something simple as follows: *.api/search_field/?category=abc,bcd,def And how would we do this in Django? Thanks -
How to pass pk from view to key_prefix function in cache_page decorator
Is it possible somehow pass “pk” from the view “ show_by_heading_view” to the function “ vary_on_paginated_or_not” using decorator/function relationship?? Only I idea how to do it that came to my mind is to analyze request and get it from there: pk = request.get_full_path_info().split("/")[-2] But it kind of unreliable way as url might get changed . I would prefer to do it pythonic way sort of but dont know how. @cache_page decorator from fancy_cache package, so it can use callable… Function “ vary_on_paginated_or_not” specifies wherther pagination is involved or not to invalidate cache if so... Thank you def vary_on_paginated_or_not(request): pk = request.get_full_path_info().split("/")[-2] count_eq = Article.objects.filter(foreignkey_to_subheading=int(pk)).count() return "show_by_heading_view+%s" % True if count_eq > 10 else False @cache_page(60*60*24*7, key_prefix=vary_on_paginated_or_not) def show_by_heading_view(request, pk): #597 current_heading = get_object_or_404(SubHeading, pk=pk) list_of_articles = Article.objects.filter(foreignkey_to_subheading=pk) if "keyword" in request.GET: keyword = request.GET["keyword"] keyword_unidecode = unidecode.unidecode(keyword) q = Q(title__icontains=keyword) | Q(content__icontains=keyword) | Q( title__icontains=keyword_unidecode) | Q(content__icontains=keyword_unidecode) list_of_articles = list_of_articles.filter(q) else: keyword = "" form = SearchForm(initial={"keyword": keyword}) paginator = Paginator(list_of_articles, 10) if "page" in request.GET: page_num = request.GET["page"] else: page_num = 1 page = paginator.get_page(page_num) context = {"current_heading": current_heading, "page": page, "list_of_articles": page.object_list, "form": form} # 597 return render(request, "articles/show_by_subheading.html", context) -
Email not showing in recipient inbox but it is sent from the Django app
I am using mailtrap.io to send email through Django's email service. The email is sent as it's shown in mailtrap's sent items but it doesn't reach the recipient. I tried using other SMTP as well such as mailjet but no email. I don't see an error in the logic none that I can understand. Kindly check. views.py def send_email(request, in_id, pr_id): invite_data = Invite.objects.get(id=in_id) person_data = PersonData.objects.get(id=pr_id) context = {'invite_data': invite_data, 'person_data': person_data} subject = "Come Join us" # email subject email_from = "settings.EMAIL_HOST_USER" # email from to_email = [person_data.person_email] # email to msg = EmailMultiAlternatives( subject=subject, body=invite_data.invite_msg, from_email=email_from, to=['pumuxum@emailtex.com'] ) print (invite_data.invite_msg) print (email_from) print (to_email) html_template = get_template( "userfiles\email.html").render() msg.attach_alternative(html_template, "text/html") msg.send() messages.success(request, ("Email Sent !!")) return redirect("InviteList") email.html <h3>Application accepted</h3> <h6>Have a good day</h6> //Data from the database {{person_data.person_first_name}} {{person_data.person_last_name}} {{person_data.person_contact_number}} <hr><hr> {{invite_data.invite_msg}} {{invite_data.event_date}} -
How to run the post_save signal after a specified time?
There is a post_save signal. Need to run it no earlier than an hour after the creation of the object. I can use time.sleep(3600), but this is not the best approach, as I understand it. What other options are there? -
django user_passes_test: Is it better to return False or raise a PermissionDenied?
According to django documentation, we can simply use the user_passes_test decorator to manage the access to a given view. The function called should return True or False depending on the test result. Now, I simply want to throw a 403 HTTP error when the test fails. Option 1 If I follow the documentation logic, I should: call the @user_passes_test(func, login_url='/errors/403') create a view def permission_denied(request): raise PermissionDenied update the urlpatterns in urls.py with: path('errors/403', views.permission_denied, name="error_403"), Option 2 Simply raise PermissionDenied in the test function instead of returning False (no need for the view and change or the urls.py) In terms of code readability, the second option seems cleaner. However, it breaks the logic of django. Would someone have an advice on which method is best? -
Render s3 template with context without actually downloading it?
I have my emails HTML on amazon-s3. I got the specific file from amazon-s3 and got its content in a variable. Now I need to render that email content with my context. Is there any way in Django to achieve it? Any built-in functions? I initially tried downloading that file from s3 but doing that was complete nonsense. So I tried this code of getting only the file content. s3 = boto3.resource( 's3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, region_name='ap-south-1' ) response = s3.Object(settings.AWS_STORAGE_BUCKET_NAME, 'static/seller_order_invoice_pdf.html').get() decoded_file = response['Body'].read().decode('utf-8').splitlines() render(None, decoded_file, context) I need to render my email content with the context I am passing. -
Connections Aborts with WinError 10053 after series of Errors in Python when using bootstrap.min.css in Django with SQL Lite
If you look at first few lines you will understand that bootstrap.min.css is linked and is accessed easily with no error. The error line starts with Favicon.ico not being available. Starting of Error The mark 1 in the image is when i open the localhost:8000. I added favicon.ico and related icons in the main directory But no luck. Ask for the things you require ...i'll reply as soon as possible. I have tried searching online and there is nothing i can find related to error which starts like this. I have all requirements complete as bootstrap is working. ERRORLOG CMD -
What's the name of the header progess bar on websites?
I'm trying to find the term for the progress bar of headers some websites now have (particularly many Microsoft documentation websites now). It seems similar to the concept of Breadcrumbs but is either a distinct version of them or something separate. An example of that I mean is here: https://www.agiliq.com/blog/2018/07/using-django-on-windows-with-wsl/ All similar search terms however (bar, breadcrumbs, headers, progress bar) have so many results for other irrelevant things that I can't seem to find the right phrase. My searching so far has landed me on breadcrumb-related sites that then discuss breadcrumbs in the header. After fairly exhaustive attempts my Google-fu has failed me; what should I be searching here? Also, my interest is particularly oriented toward implementing the same thing in a Django/Wagtail website. I'd be happy to just get the name of what I should be searching here, but if anyone has specific pointers toward good resources for how to implement in that framework that would be even one step better. -
Passing multiple responses to D3.csv function
I have a D3js website up and running. The approach I am following is getting files from aws S3 and creating url patterns and then use them with d3.csv functions. It is taking too much time to load all the visualizations because it is hitting AWS S3 five times to get 5 different CSVs as datasource. sample code for views.py is given below - def func1(request): LOCAL_PATH = '/var/www/dashboard/templates/graph/' AWS_ACCESS_KEY_ID = '*********' AWS_SECRET_ACCESS_KEY = '***********' bucket_name = 'bucket_name' # connect to the bucket conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.get_bucket(bucket_name) # go through the list of files bucket_list = bucket.list() for l in bucket_list: keyString = str(l.key) if os.path.exists(LOCAL_PATH+keyString): os.remove(LOCAL_PATH+keyString) #this deletes the file l.get_contents_to_filename(LOCAL_PATH+keyString) csv_data = open('/var/www/dashboard/templates/graph/file1.csv', 'r+').read() response = HttpResponse(csv_data,content_type='text/csv') return response I have created 5 functions for 5 files I have used as datasource for my dashboard. urls.py code - urlpatterns = [ path('', views.graph, name='graph'), path('func1/', views.func1, name='func1') ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = format_suffix_patterns(urlpatterns) I have added 5 url patterns for all the files. javascript file with d3.csv function - d3.csv("/func1/", function(data) { freqData = data.map(function(d) { return { hour: d.hour, freq: { val1: +d.val1, val2: +d.val2, val3: +d.val3, val4: +d.val4 }} }); dashboard('#id',freqData); }); The … -
Developing with celery and docker
I have noticed that developing with celery in container, something like this: celeryworker: build: . user: django command: celery -A project.celery worker -Q project -l DEBUG links: - redis - postgres depends_on: - redis - postgres env_file: .env environment: DJANGO_SETTINGS_MODULE: config.settings.celery if I want to do some changes on some celery task, I have to completly rebuild the docker image in order to have the latest changes. So I tried: docker-compose -f celery.yml down docker-compose -f celery.yml up Nothing changed, then: docker-compose -f celery.yml down docker-compsoe -f celery.yml build docker-compose -f celery.yml up I have the new changes. Is this the way to do it? seems very slow to me, all the time rebuilding the image, is then better have the local celery outsite docker containers? -
Django-rss-plugin not working for same origin urls
I am having trouble using the same origin URL in Django RSS plugin. I am using this plugin here to display feeds on my website. This is only a problem when the feeds I am using come from the same website e.g using local server my website is at http://127.0.0.1 and the feeds are accessed at http://127.0.0.1/rss. This never works. But if the website is at http://127.0.0.1 and feeds at a different server like http://www.example.com/rss this works well. Also using the website at http://www.example.com/rss to access feeds at http://127.0.0.1/rss works well I expect it to work with when the feeds and the website are on the same host address but this is not the case What might be the problem? -
AttributeError 'str' object has no attribute 'read'
I want to integrate my existing PHP app with new Django framework. I am using the django-php-bridge https://github.com/winhamwr/django-php-bridge What i want is to be authenticated into the django app by using existing PHP authentication method. I am able to generate session key by PHP and want to put it on Django Session table using the bridge. but i am running into errors. can you suggest a better alternative to the problem ? def _unserialize(): type_ = fp.read(1).lower() if type_ == b'n': _expect(b';') return None if type_ in b'idb': _expect(b':') data = _read_until(b';') if type_ == b'i': return int(data) if type_ == b'd': return float(data) return int(data) != 0 if type_ == b's': _expect(b':') length = int(_read_until(b':')) _expect(b'"') data = fp.read(length) _expect(b'"') if decode_strings: Request Method: | GET -- | -- http://localhost:8000/ 2.2.2 AttributeError 'str' object has no attribute 'read' C:\xampp\htdocs\test\dbs\env\lib\site-packages\phpserialize.py in _unserialize, line 473 C:\xampp\htdocs\test\dbs\env\Scripts\python.exe 3.7.3 ['C:\\xampp\\htdocs\\test\\dbs', 'C:\\xampp\\htdocs\\test\\dbs\\env\\Scripts\\python37.zip', 'C:\\xampp\\htdocs\\test\\dbs\\env\\DLLs', 'C:\\xampp\\htdocs\\test\\dbs\\env\\lib', 'C:\\xampp\\htdocs\\test\\dbs\\env\\Scripts', 'c:\\users\\arjun soota\\appdata\\local\\programs\\python\\python37-32\\Lib', 'c:\\users\\arjun soota\\appdata\\local\\programs\\python\\python37-32\\DLLs', 'C:\\xampp\\htdocs\\test\\dbs\\env', 'C:\\xampp\\htdocs\\test\\dbs\\env\\lib\\site-packages'] Thu, 20 Jun 2019 11:46:50 +0530 -
How to solve static files of other app can't load to my app in Django?
I use https://github.com/adamcharnock/django-adminlte2 as my template base. However, when debug false, static file use in that template can't not load. I tried to use python manage.py collectstatic but it doesn't fixed. How to make to load that template static files? May I need to copy all adminlte2 static file to project static folder? I use default wsgi server and there is no apache, nginx. I am totally new to django and python. -
Django send image with Json object and arrays
I have this view: class CommitmentList(generics.ListCreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = CommitmentSerializer .... and this serializer: class CommitmentSerializer(serializers.ModelSerializer): commitment = serializers.ListField(child=serializers.DictField(), write_only=True) class Meta: model = Commitment fields = .... my model: class Commitment(models.Model): signature = models.ImageField(upload_to='signatures/') dealer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='dealer_commitment') grower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='grower_commitment') is_original = models.BooleanField(default=True) I in json it look like: { "dealer": "123", "grower": "321", "signature": IMAGE HERE "commitment": [ { "brand": 3, "is_original": true, "commitment_unit": 300 } ] } In the postman i to try send data like this(for test) But in the postman i have an error: { "dealer": [ "This field is required." ], "grower": [ "This field is required." ], "commitment": [ "This field is required." ] } Then i tryed to add parser_classes = (MultiPartParser, ) in my view and it look like: class CommitmentList(generics.ListCreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = CommitmentSerializer parser_classes = (MultiPartParser, ) But now in the postman i have an error: A server error occurred. Please contact the administrator. And in Django project a have an error: AttributeError: 'NoneType' object has no attribute 'decode' How i can to send data like this?: { "dealer": "123", "grower": "321", "signature": IMAGE HERE "commitment": [ { "brand": 3, "is_original": … -
how to code to create a new table for every user register on site
As my site performing a specific task of user which need a db. So, how to code to create a new table in db every time a user register on site using django or mysql. -
How can I use fieldsets with a partial template in admin.py?
In admin.py I'm using fieldsets to display my fields in the change view. I want to keep using fieldsets, but also add a partial html template that renders an editable table on the same view. I've looked through the django docs and I haven't been able to find a way to include both fieldsets and add a template https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#modeladmin-objects -
How to efficiently check if name exists in database
I would like to efficiently check if a certain name is shared by any other name of the items of a shop Of course I could just cycle through all of the items in the shop and compare their names, but I'm sure that there is a contains() sort of method, just for the name. Perhaps using filter()? But how? There are too many broad answers and I can't figure it out for my unique problem models.py ... class Item(models.Model): item_name = models.CharField(max_length=200) ... class Shop(models.Model): shop_name = models.CharField(max_length=200) items = models.ManyToManyField('Product') ... views.py ... def check(name): if name in Shop.items.filter(name) # do something ... My code doesn't seem to pick up that there are any items with the same name in the shop (even though I can prove that there is) -
django serialize and deserialize object with SerializerMethodField
I'm using djangorestframework 3.7.7 I have 'Item' model which doesn't include 'owner' field. The item model serializer looks something like this: class ItemSerializer(serializers.ModelSerializer): id = serializers.CharField(required=False, max_length=1000, allow_null=True) owner = serializers.SerializerMethodField() class Meta: model = Item fields = [ 'id', 'owner' ] def get_reviewer(self, item): return item.package.reviewer if item.package else None When serializing it using: ser_item = ItemSerializer(item) I get the owner field in ser_item.data But when deserializing, using: serializer = ItemSerializer(data=ser_item) serializer.is_valid(raise_exception=True) obj = Item(**serializer.validated_data) The obj doesn't contain the owner field. It doesn't even seem to go through the serializer (when debugging). Any idea how can I deserialize so this fields, which is not part of the model will be part of the new instance? -
Is there any interest using more than 1 worker when you only have a singe core?
I'm currently setting up a Gunicorn application on a single core machine, and I have a limitation on memory so I would rather use 1 Worker and 8 threads than 2 workers with 4 threads. However, I still asking myself about a possible performance issue with a 1 worker configuration as on the Gunicorn official documentation recommend using the following setting. 2 * (number of cores) + 1 Considering the fact that with Python I'll be natively blocked by the GIL If I want true parallelism using threads, I still don't see any interest using more processes than the number of core. -
what is mysite.socket in uwsgi-tutorial?
i'm trying to find out configuration of Nginx , Uwsgi , django and socket to run my project on server . I found this tutorial , that I'm moving forward on it all the steps went well but know i'm stuck in this socket part.the error say 2019/06/20 02:31:37 [error] 9546#9546: *19 connect() failed (111: Connection re$ i try below as tutorial say: uwsgi --socket mysite.sock --wsgi-file test.py --chmod-socket=666 # (very permissive) and uwsgi --socket mysite.sock --wsgi-file test.py --chmod-socket=664 # (more sensible) but the problem still exist and same error appear in nginx log.any help to pass this step?thank you -
How to upload excel file and read it insert into database in dango
I want to read excel file and whatever that excel file containing data that data insert into MySQL when uploading excel file using Django