Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send some button value while logged in in Django?
I have a problem, I want to submit while logged in and pass value of button (Some_value) further. Without using csrf in form, debug mode suggests me using csrf_token, when I do - like in following code, it gives me HTTP ERROR 405 In HTML <td align="right"> <form action="reg_this" method="post"> {% csrf_token %} <button name="team_reg" value="Some_value">send this</button> </form> In views.py class Confirmation(BaseView): template_name = "my_page.html" @csrf_exempt def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print(context) return context In urls.py url('^app/reg_this', views.Confirmation.as_view(template_name="my_page.html")), What am I doing wrong? Thank you for answers. -
How to use pagination for mptt comments in DetailView?
How to paginate mppt comment models correctly? class ProfileDetailView(DetailView, MultipleObjectMixin): model = User template_name = 'modules/accounts/profile/profile.html' context_object_name = 'profile' queryset = User.objects.all() paginate_by = 6 def get_queryset(self): qs = self.queryset.filter(slug=self.kwargs['slug']).prefetch_related( Prefetch('comments', queryset=Comment.objects.all().select_related('created_by').prefetch_related('rating')), Prefetch('rating', queryset=Rating.objects.all().select_related('created_by')), 'following') return qs def get_context_data(self, *, object_list=None, **kwargs): object_list = self.object.comments.all().select_related('created_by').prefetch_related('rating', 'content_object') context = super(ProfileDetailView, self).get_context_data(object_list=object_list, **kwargs) context['title'] = _('Страница пользователя: ') + str(context['profile']) context['form'] = CommentCreateForm return context def post(self, request, *args, **kwargs): view = CommentCreateView.as_view(content_object=self.get_object()) return view(request, *args, **kwargs) template: {% recursetree object_list %}some template{% endrecursetree %} and I get an error on page 2: The <class 'list'> node is at a level less than the first level -
Exclude Logged in User inside forms.py
Inside my forms.py I have a list with users you want to share the upload with. My issue is that I don't know how to pass the information which user is currently logged in from my views.py (request.user I can access there ) to my forms.py In the image below the first entry should vanish forms.py share_with = forms.MultipleChoiceField( choices=tuple(UserProfile.objects.values_list('id', 'full_name')), widget=forms.CheckboxSelectMultiple, ) models.py [...] share_with = models.ManyToManyField(UserProfile) [...] views.py @login_required def upload_dataset(request): form = UploadDatasetForm() if request.method == "POST": print('Receiving a post request') form = UploadDatasetForm() if form.is_valid(): print("The form is valid") dataset_name = form.cleaned_data['dataset_name'] description = form.cleaned_data['description'] # datafiles = form.cleaned_data['datafiles'] share_with = form.cleaned_data['share_with'] instance = Datasets.objects.create( uploaded_by=request.user.profile.full_name, dataset_name=dataset_name, description=description, # datafiles = datafiles, upvotes=0, downvotes=0, ) for i in share_with: print(i) instance.share_with.add(i) return redirect("public:data") print("The Dataset has been uploaded") context = {"form": form} return render(request, "upload_dataset.html", context) -
How to display django queryset values in templates using javascript
I am trying to display list of names from a django queryset using , Here is my code def vfunc(request): context={} bats = Bat.objects.all().order_by('-id') context['bats'] = bats [each.batname for each in bats] # Gives all the batnames. return render(request, 'bat.html', context) I want to display batnames on template $(function() { //This works when I hardcode the values var batData = [{ "bat":"batname1", //hardcoded & displayed in 1st row }, { "bat":"batname2", //hardcoded & displayed in 2nd row }]; $("#CleanDatasNames").dxDataGrid({ dataSource: batData, ... ... } I am tried something like var batData = [{"bat":"{{bats|join:', ' }}"] but it is displaying obj1,obj2 in same row,I also tried to loop through but failed , any help will appreciated. -
Form not passing through? object of type 'NoneType' has no len()
im a beginner in python, django coding. I got a webpage and was tasked to allow the data to be save using forms. But i cant seem to get the data out after cleaning. It seems to have no value after cleaning. Here are my codes: In forms.py class DeviceDetailForm(ModelForm): class Meta: model= DeviceDetail fields= '__all__' def clean(self): cleaned_data = super(DeviceDetailForm, self).clean() hostname = cleaned_data.get('hostname') if len(hostname) < 8: raise forms.ValidationError('Hostname needs to be more than 8 character long, ' + hostname ) In views.py def device_add(request): if request.method == "POST": device_frm = DeviceForm(request.POST) if device_frm.is_valid(): new_device = device_frm.save() devices = Device.objects.all() return render(request, 'interface/device_display.html',{'devices':devices}) dd_frm = DeviceDetailForm(request.POST) di_frm = DeviceInterfaceForm(request.POST) if dd_frm.is_valid() and di_frm.is_valid(): if dd_frm.is_valid(): dd_frm.save() devicedetail = dd_frm.save(commit=False) devicedetail.save() dd_frm.save_m2m() deviceinterface = di_frm.save(commit=False) deviceinterface.hostname = devicedetail.hostname deviceinterface.save() else: device_frm = DeviceForm return render(request, 'interface/device_add.html',{'form':device_frm} ) dd_frm = DeviceDetailForm() di_frm = DeviceInterfaceForm() context = {'dd_frm':dd_frm, 'di_frm':di_frm, 'title':'Device Add'} return render(request, 'interface/device_add.html',context) In models.py class DeviceDetail(models.Model): hostname = models.CharField(max_length=50) mgt_interface = models.CharField(max_length=50) mgt_ip_addr = models.CharField(max_length=30) subnetmask = models.CharField(max_length=30) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) device_model = models.CharField(max_length=50) -
Display uploaded images in the website - Django
I have been trying to display my images in my html page and I did do it correct but it wont work I don't know why this is the last update of django I have watched and read alot of videos and article and do the same as they told me to do but it not working the image wont work in my html template Hope anyone can help me with this Thank you admin.py from django.contrib import admin # Register your models here. from .models import * admin.site.register(slideshowgo) settings.py STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ BASE_DIR / 'static', ] MEDIA_ROOT = BASE_DIR / 'static/images' models.py from django.db import models class slideshowgo(models.Model): image_one = models.ImageField(null=True,blank=True) slideshow html <div class="slide"> <img class="mySlides imgslide" src="{{slideshowgo.image_one.url}}"> </div> urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('card_store.url')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to combine subtitles in Python Django?
I'm writing an classifieds page. When he adds an advertisement in "the city" field, the city extracted from the offer is added. But cities do not count, and so I have, for example, Paris, Paris, Paris, Rome. How to fix it? enter image description here -
cannot read static files after deploying my project on pythonanywhere
I dont know if I did this right but during development phase I placed all my static files on my project's main directory, it looks like this: myproject myapp manage.py myproject - settings.py - urls.py ... static - css - somecssfile.css - js - somejsfile.js ... templates now my settings.py file looks like this: STATICFILES_DIRS = [BASE_DIR / "static"] STATIC_URL = '/static/' after I deployed my project into pythonanywhere I added STATIC_ROOT: STATIC_ROOT = '/home/jeremiramos/cvs/staticfiles/' it does copy my static files to staticfiles folder when I do collectstatic on pythonanywhere console but it cannot read/load the static files I used on each and every page including admin page. and my staticfiles settings on pythonanywhere looks like this: I've tried checking the forums of pythonanywhere.com but it doesn't seem to help. Can anyone please explain what did I do wrong and what should I do? Thank you! -
Context processor ('AnonymousUser' object is not iterable)
In my context processor.py file I filter a table according to a user. This all works fine : def subject_renderer(request): return {"Calicount": Tools_Calibrated.objects.filter( user=request.user, calibrated=True, issued=True).count(), } The problem comes in when I log out and try log back in. Because there is no authenticated user at login I cannot call the query in the context processor. Question: Why is my context processor function being called when I am not calling the key in the login view template. I know how to solve this with templates but I was wondering how to solve it with context processors. Essentially omit it from one view. Thank you in advance -
Django Rest api - How to insert data from multiple tables into a single table
I have written a query where i'm just selecting different columns from multiple tables. I'm learning Django rest apis and i want to write an api where the data inside my query gets inserted into my custom dump table. Would really appreciate it if you could answer my question in brief. This is my query. query= """ select pa.height, pa.weight, pa.muac, pa.tsf, pa.bmi, pa.nutritionist_comment, pa.create_date_app_side, hp.gender, hp.name, hp.regn_date_hospital, hp.dob, hp.city, hp.diagnosis_list_id, hp.diagnosis_stage, hg.first_name, hg.phone_number, hg.preferred_language_id from patientcounselling_anthropometric as pa join hospital_patient as hp on hp.uuid=pa.patient_uuid join hospital_guardian hg on hg.patient_uuid=hp.uuid """ -
Django what to use instead of null?
I am doing return of investment calculation (ROI) and the formula is ((Net returns - Actual investment) / Actual investment ) * 100 For Ex: (( 2000 - 1000 ) / 1000 ) * 100 = 100% So in this, there is an problem: Initially the returns would be 0 until returns actually comes in ! By that, the above calculation shows -100% so i thought of using Null initally, so that if its null we can show 0% and when the value changes from null to something we can show respective ROI. The problem is, i cant perform addition on Null value, _investment = F('returns') + 2000 _investment .save() As the returns field is set to null F expression couldn't perform addition operation, so how to handle this ? As i cant set the default value as "0" and use if condition base on it - because there may be some negative returns also. Please suggest some way to tackle this ! -
AJAX function is called twice
I'm building an app with Django and AJAX, and I'm having trouble with AJAX, because every time a view is called, it's done twice. For example, I have a DataTable in which I display a data series, and this DataTable is constructed after making an AJAX call to the view in Django, and this is executed twice ... I put the code below: analysis.js: function analysis_attributes_list() { $.ajax({ url: "/analysis/analysis_attributes_list", type: "GET", dataType: "json", success: function (response) { if ($.fn.DataTable.isDataTable('#top_chart')) { $('#top_chart').DataTable().destroy(); } $('#top_chart tbody').html(""); for (let i = 0; i < response["top_chart"].length; i++) { let row = '<tr>'; for (let j = 0; j < response["top_chart"][i].length; j++) { if (j !== 5) { if (response["top_chart"][i][j] === true) { row += '<td>' + '<input class="form-check-input" type="checkbox" value="" onchange="analysis_attributes_list_checkbox_handler(this)" checked>' + '</td>'; } else if (response["top_chart"][i][j] === false) { row += '<td>' + '<input class="form-check-input" type="checkbox" value="" onchange="analysis_attributes_list_checkbox_handler(this)">' + '</td>'; } else { row += '<td>' + response["top_chart"][i][j] + '</td>'; } } } row += '</tr>'; $('#top_chart tbody').append(row); } $('#top_chart').DataTable({ "pageLength": 5, "lengthMenu": [[5, 10, 20, -1], [5, 10, 20, 'All']], "destroy": true, "select": true, "responsive": true, }); }, error: function (error) { console.log(error); } }); $(document).ready(function () { analysis_attributes_list(); }); … -
Find STL File Weight Using Python Django
I want to make website with django. I want to calculate Stl File weight with infill density. User upload STL file and enter infill density on website than i want to calculate STL file weight like cura or any slicer application. How can i calculate it. I don't find any library. Thanks -
Change the name of the "Add" button in Django Admin
As we known, there is an "Add" button in each model in django admin site. How can I change the name of it into like "Add Student" to make it customerized. -
How to SEND user interaction data to database in Django
I am using a JavaScript script which when embedded into HTML will store user interaction with website, for example if website is an e-commerce site - then script will collect links, buttons clicked by user such as buy, sell, my orders, Wishlist etc. You can view the live interaction here :- https://sauravfouzdar.github.io/Web-Tracker/ Github repo link with Js script :- https://github.com/sauravfouzdar/Web-Tracker Now I want store these collected objects into a database using Django. This is where I need help // Gather Additional Data and Send Interaction(s) to Server __sendInteractions__: function () { var interactor = this, // Initialize Cross Header Request xhr = new XMLHttpRequest(); // Close Session interactor.__closeSession__(); // Post Session Data Serialized as JSON xhr.open('POST', interactor.endpoint, interactor.async); xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); xhr.send(JSON.stringify(interactor.session)); return interactor; } -
Creating a Python options console that's widely accessible
I've been making a program that uses specific settings from a settings file. This has been my first programming project, and I've been using it as an excuse to learn more in-depth stuff in Python. The settings used by the program are primarily bools indicating what the main program should and shouldn't pay attention to when operating. The first iteration of the program used a config.py file within the environment to simply import config. This didn't work so well as I had to keep editing this specific file, which as it got longer with more settings became harder to maintain. I recently learned to use Tkinter to make a separate config application where I could simply use checkboxes to set the bools. I've been using that since, but there's still one issue with it: Accessibility. The program runs on a Raspberry Pi which I don't normally use and just runs as a server. The main program gets called from a cronjob at 4 AM each day, which loads the settings from a JSON file created by the aforementioned settings GUI. As it stands, I need to use Teamviewer to actually use this GUI so while I'm proud of what I've … -
How to dumpdata in django inside the code [duplicate]
I know you could dump your data with following command in terminal: python manage.py dumpdata auth.user --pk 3 now assume I want to dumpdata inside my code not in terminal. Because I need the result jsons coming from dumpdata command. How can I do that? -
Field 'id' expected a number but got <taggit.managers._TaggableManager object
I am building a BlogApp i am stuck on an Error. What i am trying to do :- I am filtering users with similar tags. BUT when i try to filter then the error is keep showing - Field 'id' expected a number but got <taggit.managers._TaggableManager object at 0x0000015B266D3288>. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) interests = TaggableManager(verbose_name='interests') views.py def test_hobbiesss(request,user_id): users = Profile.objects.filter(interests=request.user.profile.interests) context = {'users':users} return render(request, 'mains/test_hobbiesss.html', context) What have i tried :- I also tried by users = Profile.objects.filter(interests=request.user.profile.interests.all()) BUT it shows this error The QuerySet value for an exact lookup must be limited to one result using slicing. Any help would be much Appreciated. Thank You in Advance. -
Celery Crontab in not Picking the tasks
I have added crontab for every 1 minute in the celery beat schedule. Migrations also done properly. can I miss anything in this code ?Is the crontab format will be correct. Thanks in advance . the crontab for minutes will work settings.py INSTALLED_APPS = [ 'app1', 'django_celery_beat', ] CELERY_BROKER_URL = 'amqp://localhost' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' from celery.schedules import crontab CELERY_BEAT_SCHEDULE = { 'task-second': { 'task': 'app1.tasks.elast', 'schedule': crontab(minute=1), } } celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() __init__.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) tasks.py from __future__ import absolute_import, unicode_literals from proj.celery import app @app.task def elast(): print("start") return "Exceuting after 1 minute" celery beat worker: celery -A proj beat --loglevel=debug --scheduler django_celery_beat.schedulers:DatabaseScheduler logformat : celery beat v5.1.2 (sun-harmonics) is starting. [2021-07-27 11:07:00,894: DEBUG/MainProcess] beat: Ticking with max interval->5.00 seconds [2021-07-27 11:07:00,916: DEBUG/MainProcess] beat: Waking up in 5.00 seconds. [2021-07-27 11:07:05,931: DEBUG/MainProcess] beat: Synchronizing schedule... [2021-07-27 11:07:05,932: DEBUG/MainProcess] Writing entries... -
Django - using a queryset to determine which choices to use for a field
With my app, a user chooses a few settings and these are saved as a GradeBookSetup object. One of the settings is a list of tuples for a choice. I have a form for Grade objects, and grade.score is determined from choices. The choices used come from the above mentioned GradeBookSetup object. I would like the form to use a list of choices based on the GradeBookSetup setting. In the code below you will see in the view that this setting is determined with gradescale = GradeBookSetup.objects.get(user=request.user) and the field gradescale.scale_mode can be passed to the form. I originally thought I could do the above query in the form, but I then learned this is not possible. So I think I am passing this gradescale.scale_mode to the __init__ method in the form, but I don't know how/if I can get this into my if / elif statements in the form. views.py def addsinglegrade(request, classroom_id, student_id): c = Classroom.objects.get(id=classroom_id) s = Student.objects.get(id=student_id) course = Course.objects.get(classroom=classroom_id) gradescale = GradeBookSetup.objects.get(user=request.user) objective_list = Objective.objects.all().filter(course=course) objective_tuple = [(o.id, o.objective_name) for o in objective_list] form = SingleGradeForm(objs=objective_tuple, gradescale=gradescale.scale_mode) context = {'student': s} context['classroom'] = c context['form'] = form if request.method == 'POST': ....... forms.py class SingleGradeForm(forms.Form): … -
DRF Get All Fields of OneToOne Model
I'm relatively new to DRF and currently stuck at an issue. After lot of trials I tried looking around but couldn't find something what I want. In case this question has already been answered please do direct me to the original question. Thanks in advance for the help! Problem: I've a profile model that has one to one relation with User model. When I create a new user object the profile object is auto created as expected. I would like to create an API such that when I execute it like api/profile/ in addition to returning the profile model fields it should also return all the fields from User model i.e. first_name, last_name, username, email etc... class Profile(models.Model): rater = models.OneToOneField(User, on_delete=models.CASCADE, related_name='approval') certified = models.ManyToManyField(Protocol, blank=True, default=None, related_name='trained') is_approved = models.BooleanField(default=False) My ProfileSerializer is as follows: class ProfileSerializer(serializers.ModelSerializer): approval = UserSerializer(read_only=True) class Meta: model = Profile fields = '__all__' When I run the API I get the following response: [ { "id": 1, "rater": 3, "certified": [], "is_approved": false } ] How can I get the following response: [ { "id": 1, "rater": 3, "certified": [], "is_approved": false, "first_name": xyz, "last_name": abc, "username": 123, "email": abc@gmail.com, } ] -
How Can I attach a web based cloud server to django website? Which is the best cloud database? [closed]
How Can I attach a web based cloud server to django website? Which could be the best cloud database? I run my web on google cloud and I want to attach a cloud database to it. But How?? -
Django filter based on ForeignKey model field
I am trying to eliminate a field of the Barcode model that is redundant. mostrecentscantime of Barcode is not needed because I can reference mostrecentscan.time. class Scan(models.Model): time=DateTimeField(default=timezone.now) barcode=ForeignKey('Barcode',on_delete=models.CASCADE,related_name='scans') location=ForeignKey(Location,on_delete=models.CASCADE) class Barcode(models.Model): barcode = CharField(max_length=50,unique=True) time_created = DateTimeField(default=timezone.now) mostrecentscan=ForeignKey(Scan,on_delete=models.CASCADE,related_name='+',null=True) mostrecentscantime=DateTimeField() The problem with eliminating mostrecentscantime arises with this query where I am trying to determine all Barcode objects where the time_created and the time of the mostrecentscan is greater than 7 days. Working Query: barcodematches = Barcode.objects.annotate( diff=ExpressionWrapper(F('mostrecentscantime') - F('time_created'), output_field=DurationField()) ).filter(diff__gte=timedelta(days=7)) I cannot simply reference mostrecentscan.time in this context. I have also tried adding an @property field to Barcode which doesn't work either. -
How to know the user is sign-in or not drf-social-oauth2 and reactjs
I set user login system with react-google-login and drf-social-oauth2 At first I post the message like this and check the user is signed in or not. http://localhost:8008/auth/convert-token Then how can I get to see if user is login or not in ReacJS?? I want to show welcome your@mail.com if user log-in class TestPage extends React.Component { render(){ return ( <React.Fragment> <GoogleLogin clientId={googleClientId} isSignedIn={true} buttonText="LOGIN WITH GOOGLE" onSuccess={(response) => handleGoogleLogin(response)} render={(renderProps) => ( <button onClick={renderProps.onClick} disabled={renderProps.disabled} type="button" class="login-with-google-btn" > Sign in with Google </button> )} onFailure={(err) => console.log("Google Login failed", err)} /> <GoogleLogout clientId={googleClientId} buttonText="Logout" onLogoutSuccess={logout} > </GoogleLogout> </React.Fragment> ); } -
Ldap search for extended attributes in python
When running an ldapsearch against active directory, to get the "extended attributes" of an object, we use the "+" operator. For example, ldapsearch -h localhost -p 1389 -D "cn=Directory Manager" \ -w password -b "dc=example,dc=com" "(objectclass=*)" "+" Can someone help me on how I can do the same query(getting the extended attributes) using python code. I am using ldap3 package on my current python code.