Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change Django-Notifications Delete Redirect
Im using django-notifications and am displaying notifications at two urls, /inbox/notifications/ and /admin/. By default when a notification is deleted the user is redirected to /inbox/notifications/, which works well when a user deletes the notification from this page. However, seeing as I am also displaying notifications on the admin page, whenever I delete a notification from there, the delete works successfully but redirects the admin to /inbox/notifications/, which is really annoying. My question is how can I change the redirect so that it either redirects to the calling page, or has logic that dicides where to redirect after success. This would be easy enough if this was my own view, but the logic for this is in the django-notifications app. Thank you. -
How to add links dynamically in html files in django?
For my project, I'm searching for articles on google news based on keyword input by the user, I want to display these links obtained from the search on my results page. this is my result.html {% extends 'base.html' %} {% block title %}Result{% endblock %} {% block content %} <h2><a href="{{link_to_post}}" target="_blank">Reported Url</a></h2> <div>Post Content: <br>{{content}}</div> <ul> {% for i in range(5) %} <li><a href="links[i]">headlines[i]</a></li> {% endfor %} </ul> <div> <a href="{% url 'home' %}">Back to Home Page</a> </div> {% endblock %} First question can I attach links in this way, without adding them to urls.py, if not how do I attach these dynamically generated links in my html file. Second, this is the error I'm getting on running this page: Could not parse the remainder: '(5)' from 'range(5)' But in the debug section inside local variables I can see that "links" and "headlines" are correct. So the problem in in this file only. I also tried enclosing "links" and "headlines" inside "{{}}" thank you -
how can i store the data input from the registration form in both User model and Profile model
I want to save the username from User model to the Profile model. // models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,blank=True,null=True) username = models.CharField(max_length=150,null=True,blank=True) image = models.ImageField(default='/pics/default.jpg',upload_to='profile_pics',blank=True) def __str__(self): return f'{self.user.username}.Profile' @property def get_image_url(self): if self.image and hasattr(self.image,'url'): return self.image.url else: return "/static/pics/default.jpg" -
How can one get a video thumbnail in Django with InMemoryUploadedFile?
Use case: mobile clients upload videos via mulitiPart/Form and my Django app stores the file on Google Cloud Storage as well as creates a model instance that points to that video. As Django's request.FILES returns a dictionary of InMemoryUploadedFiles, it makes using mainstream python video processing libraries difficult. All these libraries (ie. CV2, MoviePy etc) expect file paths to a video in order to extract frames but I do not have a file paths, Django only provides InMemoryUploadedFiles. Does anyone have any solutions in mind to create a video thumbnail given the time in the video? Please steer clear of solutions that involve saving the InMemoryUploadedFile to a temporary file as the uploaded videos may be quite large. The file already lives in memory, there must be a way to do this. -
Sending data to two diffrent fields using foreign key
I am using foreign key of a model person using both its field in other other model company.But while inserting data in company i am not getting last name,output is employee and last bothe same class Person(models.Model): first_name = models.CharField(max_length=30,null=True) last_name = models.CharField(max_length=30,null=True) def __str__(self): return str(self.first_name) class Company(models.Model): name=models.CharField(max_length=20,null=True) employee=models.ForeignKey(Person,on_delete=models.CASCADE,related_name='first',null=True) last=models.ForeignKey(Person,on_delete=models.CASCADE,related_name='second',null=True) def __str__(self): return str(self.name) ViewSet class CompanyViewset(viewsets.ViewSet): def create(self,request): name=request.data.get('name') employee=request.data.get('employee') last=request.data.get('last') user=Company() user.name=name user.employee=Person.objects.get(first_name=employee) user.last=Person.objects.get(last_name=last) #print(user.last) #user.last=use.last_name print(user.last.last_name) user.save() return Response({'succesfully saved'}) -
Beginner Level Question Django 3.0: Class based views
I am stuck at some beginner level concept of django. I am so much unable to understand documentation of TemplateView. In following sample of code: class ProductView(TemplateView): template_name = "product.html" Form just template_name how django render html page. I mean is template_name is reserved keyword? What if I write template_name1 instead of it will it work? And I am not returning anything how this single doing all things. -
How to reverse to a View class?
This is my views.py file. I want to reverse into PollView in the end of vote function but I am getting an error. ERROR: views.py from django.shortcuts import render, reverse, redirect from django.views import View from .models import Question, Choice # Create your views here. class PollView(View): def get(self, request): questions = Question.objects.all() return render(request, "app/poll.html", {'questions': questions}) def vote(request, pk): choice = Choice.objects.get(pk=pk) choice.votes += 1 choice.save() return reverse('poll:index') urls.py from django.urls import path from .views import PollView, vote app_name = 'poll' urlpatterns = [ path('', PollView.as_view(), name='index'), path('vote/<int:pk>', vote) ] -
Django Auth : How are many-to-many relationship models are created?
django.contrib.auth.models have only 3 models, User, Group, Permission, as per the doc and code. Doc does say groups and permissions are many-to-many relationships. But when we migrate how come other relations user_group, user_permissions, group_permissions are created? -
Nginx Docker Static File Permission Issue in Centos with Default nginx user in new version of NGINX
I am facing static files access issue using nginx as the proxy server inside docker container .I a getting permission issue .I am using Nginx+Django+Gunicorn+Docker . I am able to access the website in the URL ,but not able to access the static files.I googled more on that and followed many steps which mentioned there.But nothing works. Even i had given read write permission to that particular folder of static files for nginx. -
Migrate tables in django from a read-only database
Is there a way to migrate all tables from an oracle read-only database to django? So basically I don't want to make any modification to my database. I just want to extract information from it. From what I found till now, is a way by using routers but I don't know how exactly to use it. Thanks, any help will be appreciated DB: oracle Django version: 2.2.12 python: 3.6 cx-Oracle: 7.3.0 -
Automatically update user_id and date fields at django into database
I'm new to Python and Django and there are some things I would like to achieve in models.py: After a user submits a form I would like to safe both the current date and the current user_id of the user into the database. I know django offers to use @property decorators for those, but the problem with that is that I would like to make SQL queries using user_id and that doesn't work with decorators. Another related question is how to establish calc fields like an automatic calculation of two values in the form before submitting. -
Django How to pass str value from link a href to view without modifying urls.py?
I wanted to ask you for your help with passing a STR value from a href link to my views.py but without modifying urls.py I am not sure if it possible, but it sounds useful I think, so maybe it is doable? Right now in order to work I have to use urls.py like this: path('my_notes/', views.my_notes, {'category': 'Python'}, name='my_notes'), But I would like to go completely "DRY" and do something like this: <a class="dropdown-item" href="{% url 'my_notes' %}" category="Python">Python</a> And in views.py: def my_notes(request): category = request.GET['category'] notes = Note.objects.filter(category__category=category, sub_category__sub_category="Notes") snippets = Note.objects.filter(category__category=category, sub_category__sub_category="Code_Snippets") context = { 'notes': notes, 'snippets': snippets, 'category': category } return render(request, 'my_notes.html', context) But with this solution i get "MultiValueDictKeyError". I googled it and I tried to convert it to dict, try to add additional "false" arguments but I can't get it to work. I am not even sure if it's right approach? Thanks and Cheers! -
Seach_fields for all models including foreign keys fields and many to many fields in django admin
class DemoModelAdmin(admin.ModelAdmin): def init(self,*args,**kwargs): self.model = args[0] self.admin_site = args[1] self.list_display = self.list_filter = list(map(lambda field:field.name,self.model._meta.fields))[1:] -
DRF : how to add user permissions to user detail api?
So I am writing a UserDetails view as follows. class UserDetailsView(RetrieveUpdateAPIView): serializer_class = AuthUserSerializer def get_object(self): return self.request.user My Serializers are as follows. class PermissionSerializer(serializers.ModelSerializer): class Meta: model = Permission fields = ('id', 'name', 'codename') class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id', 'name') class AuthUserSerializer(serializers.ModelSerializer): groups = GroupSerializer(many=True) # permissions = PermissionSerializer(many=True) # permissions = serializers.PrimaryKeyRelatedField(many=True, queryset=Permission.objects.all()) class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined', 'groups', 'user_permissions') groups = GroupSerializer(many=True) gives me following. "groups": [ { "id": 2, "name": "A" }, { "id": 1, "name": "B" }, { "id": 3, "name": "C" } ], I expect the similar from permissions = PermissionSerializer(many=True) but I get the following error. Got AttributeError when attempting to get a value for field `permissions` on serializer `AuthUserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'permissions'. but instead, if add user_permissions to the fields directly without adding related reference it gives me all ids of permissions. I want to have id, name, codename also. And, Of course, UserPermissions model is not found. ;-( How … -
Django model not using another model via a foreign key relationship
I'm trying to create a web app that will allow booking onto training sessions in a running club. I've got my users app and a training_sessions app where coaches can post sessions. They include location, date, the coach taking the session and some details on what the session entails. I now want to add a facility where a logged in user can click on the session and have them booked onto it. I've a ClubSession model: class ClubSession(models.Model): location = models.CharField(max_length=200) coach = models.ForeignKey(CustomUser, on_delete=models.CASCADE) date = models.DateTimeField(default=now) details = models.TextField() def __str__(self): return self.location def get_absolute_url(self): return reverse('session_detail', args=[str(self.id)]) From it's used in several views to create, edit, delete, view and list all sessions: class SessionListView(ListView): model = ClubSession template_name = 'club_sessions.html' context_object_name = 'all_club_sessions_list' class SessionDetailView(DetailView): model = ClubSession template_name = 'session_detail.html' context_object_name = 'club_session' class SessionCreateView(CreateView): model = ClubSession template_name = 'session_new.html' fields = ['location', 'coach', 'date', 'details'] class SessionUpdateView(UpdateView): model = ClubSession template_name = 'session_edit.html' fields = ['location', 'coach', 'date', 'details'] class SessionDeleteView(DeleteView): model = ClubSession template_name = 'session_delete.html' success_url = reverse_lazy('home') I'm now trying to create a booking model with a foreign key to my user and ClubSessions models. This is what I've got: class … -
Django - How to include all possible months / quarters / year within range in queryset
I am trying to get the sum of the estimated revenue of projects within a varying range of months, but the issue I am facing right now is that the queryset I receive would leave out the months where no data exists, but I would like to receive data about that month too (with estimated revenue sum 0) so that my data visualisation would be proportional and include all months within the selected range. Here is my code: start = datetime.strptime(self.request.query_params.get('start'), '%Y-%m-%d') end = datetime.strptime(self.request.query_params.get('end'), '%Y-%m-%d') qs = SalesProject.objects.filter(sales_department=d).filter(creation_date__range=(start,end)) qs = qs.annotate(date=TruncMonth('creation_date')).values('date').annotate(est_rev_sum=Sum('sales_project_est_rev')) start and end are parameters passed in through the api call and the parameters dictate the range of months to get. Hence, for example, if start is April 2020 and end is June 2020, and there are only SalesProject instances with 'creation_date' in April and June 2020, but none in May 2020, the qs returned would only have: [{ 'date': April 2020, 'est_rev_sum': 300 }, { 'date': June 2020, 'est_rev_sum': 600 }] but what I would want is for May 2020 to be included as well (even if the sum is 0 and no instances of SalesProject exists in May2020) [{ 'date': April 2020, 'est_rev_sum': 300 }, { … -
How to run celery periodic task to some specific date only based on some fields?
I want to run my task till the task.scraping_end_date every task.search_frequency hrs if task.status is either 0 or 1. If the current date passes the scraping end date then I want to change the status as completed and stops the task. How can I do it with celery ? models class Task(models.Model): INITIAL = 0 STARTED = 1 COMPLETED = 2 ERROR = 3 task_status = ( (INITIAL, 'running'), (STARTED, 'running'), (COMPLETED, 'completed'), (ERROR, 'error') ) FREQUENCY = ( ('1', '1 hrs'), ('2', '2 hrs'), ('3', '3 hrs'), ) name = models.CharField(max_length=255) scraping_end_date = models.DateField(null=True, blank=True) status = models.IntegerField(choices=task_status) search_frequency = models.CharField(max_length=5, null=True, blank=True, choices=FREQUENCY) tasks.py scrapyd = ScrapydAPI('http://localhost:6800') @periodic_task(run_every=crontab(minute=1), ignore_result=False) def schedule_task(pk): task = Task.objects.get(pk=pk) if task.status == 0 or task.status == 1 and not datetime.date.today() >= task.scraping_end_date: # do something else: task.status = 2 task.save() -
Pass input from django-ploly-dash app to other apps of the same django template
I am using django-plotly-dash to insert a set of dash apps, representing each an individual graph, into a django template. Each app or graph has their own input fields to select data and plot it for a given time-frame. Now I would like to move the date-select/input field to one separate dash app, in order to select the data for all apps within the template but I struggle to find a a solution. I consulted the documentation at https://django-plotly-dash.readthedocs.io as well as the examples at https://djangoplotlydash.com/. Any hints on how to move forward are highly appreciated! -
Passing value(0) to empty json response in django
When a null response is sent to ajax there is no change in the chart or table.So, if there is null data sent I want the ajax response.So, for that when json data is sent,I want the output 0 instead of empty JSON response. Example: Problem:{"time_chart": {}, "pie_chart": {"super": 0, "staff": 0, "active": 0, "inactive": 0}, "table_chart": []} Note: How the time_chart responses is null and so is table_chart.I want my output something like this. Expected Output: {"time_chart": {"datetime": [8, 7, 6, 5, 4, 3, 2, 1],count": [0, 0, 0, 0, 0, 0, 0, 0]}, "pie_chart": {"super": 0, "staff": 0, "active": 0, "inactive": 0}, "table_chart": [{"username": "", "email": "", "date_joined": ""}]} The view is used to filter certain number of user in given time period.It also distingushes the type of user(Super,Staff or Active). def get_user_type(user): if user.is_superuser and user.is_staff and user.is_active: return "super" elif not user.is_superuser and user.is_staff and user.is_active: return "staff" elif not user.is_superuser and not user.is_staff and user.is_active: return "active" else: return "inactive" def midnight_time(): today = date.today() midnight = datetime.combine(today, datetime.min.time()) return midnight def midnight_yesterday_time(): today = date.today()-timedelta(days=1) midnight = datetime.combine(today, datetime.min.time()) return midnight def hits_in_yesterday(self): today = date.today() midnight = datetime.combine(today, datetime.min.time()) yesterday_hits=midnight-timedelta(days=1) return self.hit_set.filter(created__gte=yesterday_hits,created__lte=midnight).count() def … -
Pass Data From Angular to Dynamically Update Jinja2 Template
I am trying to find out how to pass data from an Angular input to a Jinja2 template that is rendered into an iframe. I understand that you can use postmessage, but I can't wrap my head around changing something like a placeholder and innerHTML in succession. I am running an Angular 8 app with a Django backend that uses Jinja2 for templates. The data sent from my Angular app is in JSON form so on initial load of the Jinja2 template it displays the correct data, but I need to update that data and reflect in in the iframe(Jinja2 template). Say I have something like this in my template <label>{{ label_text }}</label> <input type="text" placeholder="{{ input_placeholder}}"> and I pass in data on initial render as such { "label_text": "This is a label", "input_placeholder": "This is a placeholder" } On initial load it is correct, but how can I change that data dynamically and display it in the iframe live? Think of this as something like the Shopify theme editor. Changing a color/placeholder/text reflects in the iframe. Thank you for reading! -
Display Django-Notifications On Any Page
I am using django-notifications and have successfully added a link to /inbox/notifications/ where a user can view their messages. Now instead of the user visiting /inbox/notifications/ to view their messages, Id like to display the users notifications within another webpage (for example on my homepage). I know I can display a list of unread messages using {% live_notify_list %}, but would like this feed to: 1- Display read and unread messages 2- Id also like it add styling, as {% live_notify_list %} just prints out the messages and metadata in very plain form. Thank you. -
xhr.upload.onprogress does not work on Chrome
I have a progress bar that stopped working sometime in the past 2 months. I found out that it works on Firefox but not Chrome. This is the AJAX request: $(document).ready(function(){ $(function () { var pleaseWait = $('#pleaseWaitDialog'); window.showPleaseWait = function () { pleaseWait.modal('show'); }; window.hidePleaseWait = function () { pleaseWait.modal('hide'); }; }); var $myForm = $('#upload-form') $myForm.on('submit', function(event){ event.preventDefault(); var form = $(event.target) var formData = new FormData(form[4]); $.ajax({ async: true, xhr: function() { var xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { console.log(e.loaded) showPleaseWait(); console.log('Percentage uploaded: ' + (e.loaded / e.total)) var percent = Math.round(e.loaded / e.total * 100); $('#progress-bar').attr('aria-valuenow', percent).css('width', percent + '%'); } }); return xhr; }, type: 'POST', url: form.attr('action'), enctype: 'multipart/form-data', processData: false, contentType: false, data: new FormData(this), success: function(data){ if (data.success) { window.location.href = data.url; } else if (data.error) { $("#top").html(data.error.title).addClass('form-field-error'); $("#div_id_title").removeClass('form-group'); } }, error: function(xhr, status, error){ alert(error); } }); }, ); }); I cannot figure this out and I cannot find any info on it. Someone please help. -
Django Template Tags Adding Html Tag
I want to add anchor tag through Django template tag . My intension is to view files in Web page itself like if the file is a .docx type then the url must be <a href="https://docs.google.com/gview?embedded=true&url=....." ></a> And if the file is a image i want to append a click on preview model , I have tried this but it doesn't work for me, This is my template tag code @register.filter def diff_docs(value): extension = os.path.splitext(value.name)[1] if extension in ['.docx', '.ppt']: return "https://docs.google.com/gview?embedded=true&url=http://ins.justgetit.in/media/next/" + value.name return "/media/" + value.name This is my html <ul> {% for file in report|to_and2 %} <li><a target="_blank" download href="{{file.filename|diff}}">{{file.filename|remove_next}}</a> </li> {% endfor %} </ul> Is there any way for it . Or can u please suggest me any substitute in Viewing files in html page -
How to fix it as the followwing error "AttributeError: 'NoneType' object has no attribute 'read"
when inserting data, It shows the error log. Only a little request has the error. There is no error when the request are Fewer requests and why ,how to fix it? Can anyone give me a hand???? 2020-06-09 10:44:16,538 - [22999:140599824701184] - root - ERROR - 671 - DraftUtilAsync - 'NoneType' object has no attribute 'read' Traceback (most recent call last): File "/home/wyz/preonline/ShenDuTool/WangYinParse/DraftUtilAsync.py", line 664, in saveConstructDraftData count = self.dbclient.insertOne(sql, param) File "/home/wyz/preonline/ShenDuTool/WangYinParse/MyDbManager.py", line 101, in insertOne self._cursor.execute(sql, value) File "/app/signdraft/lib/python3.6/site-packages/DBUtils/SteadyDB.py", line 605, in tough_method result = method(*args, **kwargs) # try to execute File "/app/signdraft/lib/python3.6/site-packages/pymysql/cursors.py", line 170, in execute result = self._query(query) File "/app/signdraft/lib/python3.6/site-packages/pymysql/cursors.py", line 328, in _query conn.query(q) File "/app/signdraft/lib/python3.6/site-packages/pymysql/connections.py", line 517, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/app/signdraft/lib/python3.6/site-packages/pymysql/connections.py", line 732, in _read_query_result result.read() File "/app/signdraft/lib/python3.6/site-packages/pymysql/connections.py", line 1075, in read first_packet = self.connection._read_packet() File "/app/signdraft/lib/python3.6/site-packages/pymysql/connections.py", line 674, in _read_packet recv_data = self._read_bytes(bytes_to_read) File "/app/signdraft/lib/python3.6/site-packages/pymysql/connections.py", line 691, in _read_bytes data = self._rfile.read(num_bytes) AttributeError: 'NoneType' object has no attribute 'read' class DraftUtilAsync(): def saveConstructDraftData(self,param,sql) dbclient = None; try: self.dbclient = MyDbManager() count = self.dbclient.insertOne(sql, param) except Exception as e: msg = traceback.format_exc() logging.error(msg) logging.exception(e) self.dbclient.dispose(2) else: draftallInfo = self.getByDraftId(count, userId); -
I can't see my elasticbeanstalk application in the browser
I have followed AWS's instructions for deploying a django application using the ebcli. It is important to note, I think, that after running eb init I am prompted to select a reigon, enter my credentials, and set my instance. Afterwhich I receive feedback that my application has been created. I checked the AWS console on the browser and I see nothing. Yes, I checked all regions. I found out that after doing eb list and eb status that the environment wasn't actually created in the eb init step so I referenced this answer: AWS Elastic Beanstalk : the command eb list shows no environments Running eb create --single allowed the application to upload and I could access via the link provided. However, this for some reason is not attached to the instances in my user and cannot see it in the browser. Why is it that I cannot see my application in the AWS console despite it existing and running currently? Here is the output of eb status Environment details for: **** Application name: ***** Region: ***** Deployed Version: app-2ecd-200609_120851 Environment ID: e-wbqx6***** Platform: arn:aws:elasticbeanstalk:ap-northeast-1::platform/Python 3.7 running on 64bit Amazon Linux 2/3.0.2 Tier: WebServer-Standard-1.0 CNAME: *****.elasticbeanstalk.com Updated: 2020-**-** 03:18:12.491000+00:00 Status: …