Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What's the best way to create a generic serializer which is able to serialize all the subclasses of the base model in Django Rest Framework?
I'm currently working on a notification system which is going to deliver many different types of notifications through an API. I have a base notification class called BaseNotification. Here is the code: class BaseNotification(models.Model): message = models.CharField(max_length=500) seen = models.BooleanField(default=True) class Meta: abstract = True And I want to subclass this model to create different variations of notifications: class InvitationNotification(BaseNotification): invited_user = models.ForeignKey(User, on_delete=models.CASCADE) campagin = models.ForeignKey(Campagin, on_delete=models.CASCADE) # ... the rest of specific fields class ChatMessageNotification(BaseNotification): contact = models.ForeignKey(User, on_delete=models.CASCADE) chat_room = models.ForeignKey(SomeSortOfChatRoomWhichIsNotImplementedYet, on_delete=models.CASCADE) # ... the rest of specific fields As you can see, each of those variations, has some meta-data associated with it. The front-end developer would be able to create user interactions using these meta data (for example, in the case of a chat message, the front-end developer would redirect the user to the chat room) I want to list all of these notifications through one unified API. For that, I need a serializer to serialize the objects as json but I don't want to have a sperate serializer for each. Ideally I want to have a generalized serializer which is capable of serializing all kinds of notifications and generates different json output depending on the … -
The number of ajax requests increases with each button click
I am creating an application with Django and AJAX and I have a problem ... I have a button that when pressed, makes a call to a view in Django using AJAX, and every time I press that button, the call is made one more time. That is, the first time I press it, it only makes 1 call, but the second makes 2, the third makes 3, and so on. I have read the rest of the questions similar to mine, but they have not worked for me... this one and many others... I have also tried with $("# button_relation").off('click').on('click', function () {...} and it works, but the page reloads, and I don't want it to reload .. . JS file: $(document).ready(function () { analysis_attributes_list(); $("#button_relation").click(function (e) { e.preventDefault(); let relation = $('#input_relation').val(); let selected = $('#selected').text(); $.ajax({ url: '/analysis/save_relation', type: 'POST', data: { csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(), relation: relation, selected: selected, }, success: function (response) { console.log(response); successNotification(response.msg); analysis_attributes_list(); $('#input_relation').val("") }, error: function (error) { console.log(error); errorNotification(error.responseJSON.msg); }, }); }); }); The view: def save_relation(request): if request.method == 'POST' and request.is_ajax(): print('save_relation') relation = request.POST.get('relation') selected = request.POST.get('selected') my_csv= pd.read_csv('my_csv.csv', sep=';', encoding='utf-8', ) my_csv = my_csv.fillna('') index = my_csv.index condition … -
Python AWS S3 Download S3 Files save in ZIP
I have a bunch of files stored on AWS S3. I want to download those find into a single zip Below is my code. import boto3 import zipfile from io import StringIO, BytesIO s3 = boto3.client('s3') s = BytesIO() zf = zipfile.ZipFile(s, 'w') file_name = '%s-files-%s.zip' % (student.get_full_name(), str(datetime.datetime.now())) files_key_list = ['file1.png', 'file3.png'] for f in files_key_list: data = s3.download_file(settings.AWS_STORAGE_BUCKET_NAME, f, f) zf.write(data) zf.close() resp = HttpResponse(s.getvalue(), content_type="application/x-zip-compressed") resp['Content-Disposition'] = 'attachment; filename=%s' % file_name return resp Error stat: can't specify None for path argument -
creating django project just doesnt work right
i create a project folder, than create a venv and do $ django-admin startproject trydjango. now when i try to run runserver it gives me an error that it couldnt find manage.py, so i have to move it to the original project folder (which now has venv, trydjango, and manage.py). this is a problem i have seen online. however, when i try to run runserver now it says "ModuleNotFoundError: No module named 'trydjango.settings'" (full traceback bellow) the weird thing is, i have opened a project file just like this before, but now its not working. i have done it in the exact same way, the exact way that tutorials show. the only thing that changed is the django version - the tutorial said to use 2.0.7 in order to be able to follow the tutorial. full traceback: File "E:\Python\projects\try_django_project\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "E:\Python\projects\try_django_project\venv\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "E:\Python\projects\try_django_project\venv\lib\site-packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "E:\Python\projects\try_django_project\venv\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "E:\Python\projects\try_django_project\venv\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "E:\Python\projects\try_django_project\venv\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import … -
Django overriding templates
When I override admin/change_form.html everything works fine except for user info in the upper right corner (logout, change password and view site options). I don't see this message. How can I make it visible? I thought that when I override a template everything works exactly as it does in the parent template except for the particular block I actually override. Am I wrong? Does it work in a different way? My code: {% extends "admin/change_form.html" %} {% load i18n admin_static admin_list %} {% block title %} Apply users to brand {% endblock %} {% block content %} <h1>Select brands</h1> {% for brand in brands %} <li> <a href="http://localhost/admin/user/user/{{brand.id}}/test/">{{ brand }}</a> </li> {% endfor %} {% endblock %} So my question is, how can I make the usertools block visible? Thanks -
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): …