Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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: … -
How to consume REST api running on the same network with android app built with Ionic?
Hi everyone I built an API with django and I can consume this with my Ionic app using my browser but when I try to connect using my real device which is an android I get "Unknown Error" message with every request to the api. In order to run my django project on another devices inside the same network I am using python manage.py runserver 0.0.0.0:8000 command settings.py (django project) ALLOWED_HOSTS = ['I got the ip with ipconfig'] CORS_ORIGIN_ALLOW_ALL=True On Ionic I send the next headers setHeaders: { 'Authorization': `Bearer ${token}` } config.xml on Ionic <?xml version='1.0' encoding='utf-8'?> <widget id="io.ionic.starter" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"> <name>MyApp</name> <description>An awesome Ionic/Cordova app.</description> <author email="hi@ionicframework.com" href="http://ionicframework.com/">Ionic Framework Team</author> <content src="index.html" /> <access origin="*" /> <allow-intent href="http://*/*" /> <allow-intent href="https://*/*" /> <allow-intent href="tel:*" /> <allow-intent href="sms:*" /> <allow-intent href="mailto:*" /> <allow-intent href="geo:*" /> <preference name="ScrollEnabled" value="false" /> <preference name="android-minSdkVersion" value="19" /> <preference name="BackupWebStorage" value="none" /> <preference name="SplashMaintainAspectRatio" value="true" /> <preference name="FadeSplashScreenDuration" value="300" /> <preference name="SplashShowOnlyFirstTime" value="false" /> <preference name="SplashScreen" value="screen" /> <preference name="SplashScreenDelay" value="3000" /> <platform name="android"> <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android"> <application android:networkSecurityConfig="@xml/network_security_config" /> </edit-config> <resource-file src="resources/android/xml/network_security_config.xml" target="app/src/main/res/xml/network_security_config.xml" /> <allow-intent href="market:*" /> <icon density="ldpi" src="resources/android/icon/drawable-ldpi-icon.png" /> <icon density="mdpi" src="resources/android/icon/drawable-mdpi-icon.png" /> <icon density="hdpi" src="resources/android/icon/drawable-hdpi-icon.png" /> <icon … -
Store django validation errors (without throwing) in model clean() method, retrieve them during model object creation?
I created a custom validation code inside a model class' clean method where validation errors are coded to be stored in error attributes instead of being thrown. Then, during object creation elsewhere in another function, it's desired the errors be either thrown and caught in try/exception block or programmatically retrieved and handled. The code snippets in those two locations are like the following. Therefore, please help in giving corrections or tips on who to go about achieving the result. Thanks! Code in models.py clean() method for validating two fields. def clean(self, *args, **kwargs): super().clean(*args, **kwargs) # Entry_ID Validation: Non negative integer – should not repeat in single file try: cast_value = int(self.watch_entry_id) if cast_value < 1: self.add_error({'watch_entry_id': ValidationError(_("Invalid Entry_ID: Non-positive integer."), code='invalid')}) except TypeError: self.add_error({'watch_entry_id': ValidationError( _("Invalid Entry_ID: Not a number."), code='invalid')}) # Customer_ID Validation: Non negative integer try: cast_value = int(self.cust_id) if self.cust_id < 1: self.add_error({'cust_id': ValidationError(_("Invalid Customer_ID: Non-positive integer"), code='invalid')}) except TypeError: self.add_error({'cust_id': ValidationError(_("Invalid Customer_ID: Not a number."), code='invalid')}) # Code in a function where model objects are created and processed. try: cwt = Cust_Watch_Time.objects.create( watch_entry_id=list_of_data_list[i][0], cust_id=list_of_data_list[i][1], # ... ) cwt.clean() field_errors.append(cwt.fields['watch_entry_id'].message_dict['invalid']) field_errors.append(cwt.fields['cust_id'].message_dict['invalid']) # ... if field_errors: raise ValidationError(field_errors) except ValidationError as e: data_with_error_msg = str(list_of_data_list[i]) + " … -
How to Change Django Default Page to your Design?
I uploaded my site to the live server, but still, I am seeing Django default page, I updated my urls.py file, but still, it's not working. and it's showing me this output. Please let me know where I am Mistaking. I am trying to access this mydomain.com/dashboard Using the URLconf defined in yoursite.urls, Django tried these URL patterns, in this order: admin/ The current path, dashboard, didn't match any of these. here is my urls.py file... urlpatterns = [ path('admin/', admin.site.urls), url(r'^dashboard/', include('dashboard.urls')), url(r'^accounts/', include('accounts.urls')), url('', include('frontpanel.urls')), path('', views.index, name='index'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And here is my views.py file... def index(request): category = Category.objects.all().order_by('created_at') return render(request, "base.html", {'category':category}) -
How To Get Notification Count From Django-Notifications
Im using django-notifications and know I can get a count of the users unread notifications like this {% notifications_unread as unread_count %} {% if unread_count == 0 %} [..cont..] However, I cannot find out how to get a count of all a users notifications (read and unread). Thank you.