Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make Icon Clickable in HTML
I am essentially trying to replace the following EDIT and DELETE buttons with icons, but am running into issues trying to do this within HTML. The OnClick function doesn't seem to do anytihng when I click the buttons. Any ideas on how to adjust this code? html <div style="height:400px; overflow:auto; margin:0px 20px 20px 20px"> <table id="userTable" class="table table-striped" style="font-family: graphik"> <tr> <th>Employee</th> <th>Description</th> <th colspan="3">Stakeholder Group</th> </tr> {% for user in users %} <tr id="user-{{user.id}}"> <td class="useremployee userData" name="employee">{{user.employee}}</td> <td class="userdescription userData" name="description">{{user.description}}</td> <td class="userstakeholder_group userData" name="stakeholder_group">{{user.stakeholder_group}}</td> <td align="center"> <button class="btn btn-success form-control" onClick="editUser({{user.id}})" data-toggle="modal" data-target="#myModal" )">EDIT</button> </td> <td align="center"> <img class="d-block w-100" src="{% static 'polls/images/edit.png' %}" style="cursor:pointer; width: 30px; height: 30px" alt="opmodel"> </td> <td align="center"> <img class="d-block w-100" onClick="editUser({{user.id}})" src="{% static 'polls/images/delete.png' %}" style="cursor: pointer; width: 30px; height: 30px" alt="opmodel"> </td> <td align="center"> <button class="btn btn-danger form-control" onClick="deleteUser({{user.id}})">DELETE</button> </td> </tr> {% endfor %} </table> </div> -
Which is the best way to bulid chat application in django with mongodb
Can any one pls suggest how to implement the chat application using django with mongodb -
How do you delete a Django Object after a given amount of time?
I'm a new Django developer, and working on a website where users can store csv files outputted by the website to a field of a model along with a randomly generated key. I referred to this link: Delete an object automatically after 5 minutes for more information, but when I implemented it onto my own project, it did not work. from django.db import models from django.utils import timezone from django.conf import settings import datetime import os # Create your models here. class TemporaryFile(models.Model): key = models.CharField(max_length = 64) data = models.FileField() time_created = models.DateTimeField(default = timezone.now) @property def delete_after_time(self): if self.time_created < datetime.datetime.now()-datetime.timedelta(minutes=1): self_file = TemporaryFile.objects.get(pk = self.pk) data = self.data os.remove(os.path.join(MEDIA_ROOT, data)) os.remove(os.path.join(BASE_DIR, data)) self_file.delete() return True else: return False Because it is difficult to store a csv file to a model field, I instead saved it to the default storage that Django has, which for some reason made two copies of the csv file and stored one in the media root and another one in the base directory. That is why I have the os.remove functions. Can somebody please tell me why the object and files are not being deleted? -
Django URL not loading response in browser, when opened from HTML file using href attribute
I am comparatively new to web development , trying to open Django URL by "href" link in HTML file. But URL response not loading fully in browser. While same link(URL), when opened directly in browser, url response loads fully. Below is the sample Django view def sampleview(request): return HttpResponse("URL response loaded fully") Sample URL for view url(r'^sampleurl/$', views.sampleview, name='sampleurl') When opening URL link directly in browser Browser shows the response as "URL response loaded fully" While when opening the link through href attributes of html view, like <a href="/sampleurl">Sample link</a></li> browser do not loads the response Have tried following: i) Making the link as `href="/sampleurl/" instead of href="/sampleurl"` ii)Using url name in the `{% url 'sampleurl' %} instead of href="/sampleurl"` but failed to resolve the issue -
(Django Migration Bug with PostgreSQL) django.db.utils.ProgrammingError: relation "subjects_subject" does not exist
**Link github to this repo : **https://github.com/thetruefuss/elmer When i start this project using sqlite for database, it migrate with database perfectly, but when i switch it to POSTGRESQL, it got this error: django.db.utils.ProgrammingError: relation "subjects_subject" does not exist LINE 1: ...ect"."created", "subjects_subject"."updated" FROM "subjects_... THE POINT IS: in this repo it already had all the migrations file for all model, u can check in this repo, and i cannot migrate this with database in pgadmin 4 db settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'demo_postgres', 'USER':'postgres', 'PASSWORD':'18092000', 'PORT':'5432', 'HOST':'127.0.0.1', } } ** my command ** python manage.py migrate subjects_subject ( migration_file) class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('boards', '0001_initial'), ] operations = [ migrations.CreateModel( name='Subject', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(db_index=True, max_length=150)), ('slug', models.SlugField(blank=True, max_length=150, null=True)), ('body', models.TextField(blank=True, max_length=5000, null=True)), ('photo', models.ImageField(blank=True, null=True, upload_to='subject_photos/', verbose_name='Add image (optional)')), ('rank_score', models.FloatField(default=0.0)), ('active', models.BooleanField(default=True)), ('created', models.DateTimeField(default=django.utils.timezone.now)), ('updated', models.DateTimeField(auto_now=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='posted_subjects', to=settings.AUTH_USER_MODEL)), ('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='submitted_subjects', to='boards.Board')), ('mentioned', models.ManyToManyField(blank=True, related_name='m_in_subjects', to=settings.AUTH_USER_MODEL)), ('points', models.ManyToManyField(blank=True, related_name='liked_subjects', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': ('-created',), }, ), ] subjects_subject(model_file) class Subject(models.Model): """ Model that represents a subject. """ title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, null=True, blank=True) body = models.TextField(max_length=5000, blank=True, null=True) photo … -
Django IntegrityError at /doctor-add-notes NOT NULL constraint failed:
I am a newbie. Enhancing a project For the current user, there are different members, for each member I want to add Notes with the current time & date. so I am using Django in-built user model. for example User1 Member1 Notes Date & Time Member2 Notes Date & Time Member3 Notes Date & Time **User2** Member1 Notes Date & Time Member2 Notes Date & Time Member3 Notes Date & Time for now just trying to add user1, member1 Notes & Date but after submitting the form getting an error. how to correct that, IntegrityError at /doctor-add-notes NOT NULL constraint failed: hospital_notes.user_id Request Method: POST Request URL: http://127.0.0.1:8000/doctor-add-notes Django Version: 3.0.7 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: hospital_notes.user_id Exception Location: C:\Users\user1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 396 Python Executable: C:\Users\user1\AppData\Local\Programs\Python\Python38\python.exe Python Version: 3.8.3 Python Path: ['C:\\Users\\user1\\PycharmProjects\\Project\\hospitalmanagement', 'C:\\Users\\user1\\PycharmProjects\\Project\\hospitalmanagement', 'C:\\Users\\user1\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip', 'C:\\Users\\user1\\AppData\\Local\\Programs\\Python\\Python38\\DLLs', 'C:\\Users\\user1\\AppData\\Local\\Programs\\Python\\Python38\\lib', 'C:\\Users\\user1\\AppData\\Local\\Programs\\Python\\Python38', 'C:\\Users\\user1\\AppData\\Roaming\\Python\\Python38\\site-packages', 'C:\\Users\\user1\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages'] Server time: Thu, 31 Dec 2020 03:37:51 +0000 Here is part of relevant code **Models** class Notes(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) report = models.TextField(max_length=500) NoteDate = models.DateField(auto_now=True) **View:** def doctor_add_notes_view(request): appointmentForm=forms.PatientNotesForm() mydict={'appointmentForm':appointmentForm,} print(mydict) if request.method=='POST': appointmentForm=forms.PatientNotesForm(request.POST) if appointmentForm.is_valid(): appointment=appointmentForm.save(commit=False) appointment.save() return HttpResponseRedirect('doctor_add_notes') else: return render(request, 'hospital/doctor_view_patient.html',{'alert_flag': True}) return render(request,'hospital/doctor_add_notes.html',context=mydict) **Forms:** class PatientNotesForm(forms.ModelForm): class Meta: model=models.Notes fields=['report'] **doctor_add_notes.html** {% extends … -
How to build a exchange software (like the Stock Market) in Django?
I am trying to build an exchange software that would handle buy and sell orders and execute transactions within Django. To be clear, this is not a software that would buy and sell existing stocks like from the US Stock Exchange and try to make a profit. Think of it as trying to create a site just like Fidelity or Robinhood where the software connects buyers to sellers and fulfills millions of transactions a day. I am trying to create the Fidelity or Robinhood, not a bot that would try to trade on Fidelity or Robinhood. Are there any packages or resources anyone is familiar with that would be helpful for this? I haven't been able to find any on my own but am sure someone has tried to do this in the past. -
Postgresql GIN index not used when query is performed with icontains
When I query the table using icontains, Django performs an SQL query using UPPER and the index seems to be useless. When I query the same table using contains the index is used. The difference is 3ms vs 240ms. Should I create a lowercase index and match with contains? (How could this be done?) Should I create a field where all the contents will be lower cased and index that field? Something else? The model: class Name(models.Model): name_en = models.CharField(max_length=127) ... class Meta: indexes = [ GinIndex( name="name_en_gin_trigram", fields=["name_en"], opclasses=["gin_trgm_ops"], ) ] The query that uses the index: >>> Name.objects.filter( Q(name_en__contains='eeth') | Q(name_en__trigram_similar='eeth') ) SELECT * FROM "shop_name" WHERE ("shop_name"."name_en"::text LIKE '%eeth%' OR "shop_name"."name_en" % 'eeth') LIMIT 21; The resulting query plan: Limit (cost=64.06..90.08 rows=7 width=121) (actual time=0.447..2.456 rows=14 loops=1) -> Bitmap Heap Scan on shop_name (cost=64.06..90.08 rows=7 width=121) (actual time=0.443..2.411 rows=14 loops=1) Recheck Cond: (((name_en)::text ~~ '%eeth%'::text) OR ((name_en)::text % 'eeth'::text)) Rows Removed by Index Recheck: 236 Heap Blocks: exact=206 -> BitmapOr (cost=64.06..64.06 rows=7 width=0) (actual time=0.371..0.378 rows=0 loops=1) -> Bitmap Index Scan on name_en_gin_trigram (cost=0.00..20.03 rows=4 width=0) (actual time=0.048..0.049 rows=15 loops=1) Index Cond: ((name_en)::text ~~ '%eeth%'::text) -> Bitmap Index Scan on name_en_gin_trigram (cost=0.00..44.03 rows=4 width=0) (actual time=0.318..0.320 rows=250 … -
Django ImageField verification
I want to verify that the uploaded image is valid. models.py def get_upload_path(instance, filename): return f'register/{instance.owner.job_number}/{filename}' class UserProfile(models.Model): name = models.CharField(max_length=64, null=True, blank=True) feature = ArrayField(models.FloatField(null=True, blank=True), null=True, blank=True, size=512) department = models.CharField(max_length=32, null=True, blank=True) job_number = models.CharField(max_length=32, null=True, blank=True) card_number = models.CharField(max_length=32, null=True, blank=True) date = models.DateTimeField() class Meta: db_table = 'UserProfile' def to_dict(self): return {'id': self.id, 'name': self.name, 'feature': self.feature} class UserRegister(models.Model): owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) image = models.ImageField(upload_to=get_upload_path) class Meta: db_table = 'UserRegister' forms class UserRegisterForm(forms.ModelForm): class Meta: model = UserRegister fields = "__all__" error_messages = { 'image': { 'invalid_image': 'error!' } } views class AddUser(View): def get(self, request): data = { 'title': 'AddUser' } return render(request, './User/add_user.html', data) def post(self, request): name = request.POST.get('name') department = request.POST.get('department') job_number = request.POST.get('job_number') card_number = request.POST.get('card_number') date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') user_profile = UserProfile.objects.create(name=name, department=department, job_number=job_number, card_number=card_number, date=date) # image = request.FILES.get('file') user_register_form = UserRegisterForm({'owner': user_profile.id}, request.FILES) if user_register_form.is_valid(): user_register_form.save() else: print(user_register_form.errors) return redirect(reverse('admin:add_user')) How do I put user_profile.id in? I try to use {'owner_id': user_profile.id} and {'owner': user_profile.id} will not work. I always thought that ImageField can be automatically verified, but in fact it doesn't. I searched some information and needed to use Forms, but I never used it. … -
Django Reverse Error upon attempting to delete account
I am unsure of what went wrong but I cannot delete my own account. I receive the following error: Reverse for 'delete_account' with keyword arguments '{'user_id': 'testuser1'}' not found. 1 pattern(s) tried: ['account/delete/(?P[^/]+)$'] NoReverseMatch at /account/2/ Views.py def delete_user(request, username): if request.method == 'DELETE': try: user = request.user user.delete() context['msg'] = 'Bye Bye' except Exception as e: context['msg'] = 'Something went wrong!' else: context['msg'] = 'Request method should be "DELETE"!' return render(request, 'HomeFeed/snippets/home.html', context=context) urls.py from account.views import ( delete_user, ) path('delete/<username>', delete_user, name='delete_account'), account.html <a class="mt-4 btn btn-danger deleteaccount" onclick="return confirm('Are you sure you want to delete your account')" href="{% url 'account:delete_account' user_id=request.user.username %}">Delete Account</a> traceback File "/lib/python3.8/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/lib/python3.8/site-packages/django/template/defaulttags.py", line 443, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "/lib/python3.8/site-packages/django/urls/base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/lib/python3.8/site-packages/django/urls/resolvers.py", line 673, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'delete_account' with keyword arguments '{'user_id': 'testuser1'}' not found. 1 pattern(s) tried: ['account/delete/(?P<username>[^/]+)$'] -
Django + Angular
i am new to the world of web development and i have a very good foundation on django for backend operations. i am also learning angular for front-end applications. so far i am quite happy writing in django for backend, but i dont like to work with the django templates. My question is, is there any way to integrate angular as the front-end portion in a django environment, keeping the django as the backend?? also while we at it, is there any good designing (UI design) courses available and where (free or paid)? -
WSGI Mod with Django and Pyenv on CentOS "no module named encodings"
I have an issue with CentOS 8 running a Django 3.0 application using Apache 2 as an httpd service. When trying to serve the application I get a dump of the environment as follows in the error_log: Could not find platform independent libraries <prefix> Could not find platform dependent libraries <exec_prefix> Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = '/srv/test/venv/bin/python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/srv/test/venv/bin/python' sys.base_prefix = '/root/.pyenv/versions/3.9.0' sys.base_exec_prefix = '/root/.pyenv/versions/3.9.0' sys.platlibdir = 'lib' sys.executable = '/srv/test/venv/bin/python' sys.prefix = '/root/.pyenv/versions/3.9.0' sys.exec_prefix = '/root/.pyenv/versions/3.9.0' sys.path = [ '/root/.pyenv/versions/3.9.0/lib/python39.zip', '/root/.pyenv/versions/3.9.0/lib/python3.9', '/root/.pyenv/versions/3.9.0/lib/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f6034d44880 (most recent call first): <no Python frame> I have the documentation and read a bit on this and there isn't a valid solution. This is the process by which I'm setting this up. I pull down the repo into /srv/test Go into that directory Create a virtual environment with virtualenv using ~/.pyenv 3.9 that I previously installed. Activate into virtual … -
Update db after successful payment - DRF
In my project I use Django as my backend, vue as my frontend and stripe as my payment processing software. The users of my program will be able to buy in game currency (points). So whenever I recieve the checkout.session.completed webhook event I essentially want to change the users' points accordingly in the db. I thought of making an internal api request, through django, that updates the users' points but I quickly found out that it would be bad practice and should only be done when testing. I was just wondering how you would tackle this problem and what you think would be the best practice in this situation. If you need any more information, just ask. Thanks in advance. -
How to make the outlinked image (included in rich text) retrieved from django template languange responsive
The out linked image which is retrieved from the rich text (article.body) stored in database can't be responsive, its size is even over the border of the cotainer, how can I get it responsive? <div class="container-xl p-3 my-3 border"> {{article.body|safe|linebreaks}} </div> The content of article.body is like the below: <h3>1 - Say the truth</h3> <p> <img alt="Check" src="https://media-exp1.licdn.com/dms/image/C4D12AQFGX-qEDVN8KQ/article-inline_image-shrink_1500_2232/0/1608331886504?e=1614816000&amp;v=beta&amp;t=FrftEfk4TS7slp1blmqoPiZbdpup_Un54SQ3WLacKWo" /> </p> <p>Everything you say Records will remain online and on networks&#39; archives. So it&#39;s h... </p> Thanks -
python: can't open file 'manage.py': [Errno 2] No such file or directory when compose docker
I run two different Apps in containers. Django App Flask App Django ran just well. I configured my Flask App as follow: This Is a docker-compose.yml version: '3.8' services: backend: build: context: . dockerfile: Dockerfile ports: - 8001:5000 volumes: - .:/app depends_on: - db db: image: mysql:5.7.22 restart: always environment: MYSQL_DATABASE: main MYSQL_USER: shedd MYSQL_PASSWORD: root MYSQL_ROOT_PASSWORD: root volumes: - .dbdata:/var/lib/mysql ports: - 33067:3306 This also is my Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app CMD python main.py Problem: When I run docker-compose up the following error occurs backend_1 | python: can't open file 'manage.py': [Errno 2] No such file or directory I don't know why it tries to open manage.py file since it is Flask and not Django App. I need your help. Thanks in Advance. -
Name error: why can't i query the number of likes and the like button in the home page through the home screen view
These are the views for my like button and home page. I am unsure of why i cannot query the number of likes and the like button in the home page, which caused this name error. Any help is greatly appreciated I'm shown that the problem lies here : blog_post = get_object_or_404(BlogPost, slug=slug) but how can i change it to define the slug, ive already tried to have more arguments for slug but it didnt work views.py def LikeView(request, slug): context = {} user = request.user if not user.is_authenticated: return redirect('must_authenticate') post = get_object_or_404(BlogPost, slug=slug) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return redirect('HomeFeed:detail', slug=slug) def home_feed_view(request, **kwargs): context = {} blog_posts = sorted(BlogPost.objects.all(), key= attrgetter('date_updated'), reverse = True) blog_post = get_object_or_404(BlogPost, slug=slug) total_likes = blog_post.total_likes() liked = False if blog_post.likes.filter(id=request.user.id).exists(): liked = True context['blog_posts'] = blog_posts context['blog_post'] = blog_post context['total_likes'] = total_likes return render(request, "HomeFeed/snippets/home.html", context) html {% for post in blog_posts %} <td class="table-primary"><form action="{% url 'HomeFeed:like_post' post.slug %}" method="POST">{% csrf_token %} <button type="submit" name="blog_post_slug" value="{{post.slug}}" class='btn btn-primary btn-sm'>Like</button> {{ total_likes }} Likes</form></td> {% endfor %} TraceBack: NameError at /HomeFeed/ name 'slug' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/HomeFeed/ … -
Apache2 WebServer with django, creating problems
I have a problem with creating a web server with apache 2 and django. I just want to set up the apache server with one site for now however in the future I may want one or two more. I am using raspberry pi OS and python3 and django 3.1 and apache 2. I am following a tutorial however there seems to be a problem with mine when running the config test and I can't work out what is wrong. I am very very new to apache and django. Here is the error message AH00526: Syntax error on line 14 of /etc/apache2/sites-enabled/djangoproject.conf: Alias must have two arguments when used globally Action 'configtest' failed. The Apache error log may have more information. and here is the file it is referencing: ServerAdmin admin@djangoproject.localhost ServerName djangoproject.localhost ServerAlias www.djangoproject.localhost DocumentRoot /home/pi/webServer ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/pi/webServer/static <Directory /home/pi/webServer/static> Require all granted </Directory> Alias /static/home/pi/webServer/media <Directory /home/pi/webServer/media> Require all granted </Directory> <Directory /home/pi/webServer/CCC> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django_project python-path=/home/pi/webServer python-home=/home/pi/webServer$ WSGIProcessGroup webServer WSGIScriptAlias / /home/pi/webServer/CCC/wsgi.py </VirtualHost> -
Radio Button that show saved selected option, with Python Bootstrap
I'm pretty new with Python Bootstrap, and I created a Python Bootstrap Form with Radio Button options for a specific field entrepot.etage I am wondering what is the best way to show which option is checked, on saved database record ? Like if "Option 2" is saved on my record, I want it checked when you edit or view with Radio Button. There is my HTML file (Just the important part) <form action="/entrepots/edit_entrepot" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="col-lg-12"> <div class="form-group"> <div class="col-sm-4"> <label class="control-label">Étage : </label> <div class="form-group"> <label class="radio-etage"> <input type="radio" name="etage" value="1">1 </label> <label class="radio-etage"> <input type="radio" name="etage" value="2">2 </label> </div> </div> <div class="form-group"> <input type="hidden" value="{{ entrepot.id }}" name="id"> <input type="submit" name="submit" class="btn btn-block btn-success" value="Modifier Entrepots"> </div> </div> </div> </form> -
Saving a QR Code in django python as base64 for to_artistic method
I would like to save my QR Code from the to_artistic method. For my other qr codes I have been doing: buffer = io.BytesIO() qr_img.save(buffer, format="PNG") qr_code = "data:image/png;base64,"+base64.b64encode(buffer.getvalue()).decode("utf-8") How can I do this for qr.to_artistic? Documentation: https://segno.readthedocs.io/en/latest/web-development.html Thanks! -
Displaying user uploaded image in Python Django
I am creating a website using the Django python framework and am currently stuck on a problem. I am using function views to display a page called myaccount, and on 'myaccount' i would like all user details to be displayed using context objects, for this page it is 'user'. I also have another model called Profile, which holds the profile picture and date of birth of the user. However when i attempt to display the image which has been uploaded during the account creation into the media folder named '/media/%y/%m/%d/imagename.filextension' i receive an error saying "The 'profilepicture' attribute has no file associated with it." I have been searching vastly for fixes to this issue and have so far found no result which has worked, i have tried to create a property function which gets the url from the image called 'get_absolute_url' by doing user.profile.profilepicture.get_absolute_url but it fails to work and displays the same error. I was wondering if anyone could point me in the direction of a fix for this or a solution. The code to display the image, views.py and urls.py is down below views.py @login_required def myaccount(request): return render(request, 'account/myaccount.html', {'section': 'myaccount'}) urls.py path('', views.myaccount, name='myaccount'), myaccount.html <img … -
How to call post_save signal after adding object to ManyToMany field on another model
I have two models, Post and Comment. Now I have a custom function using post_save signal on a comment object. However, since I add the object to the many to many field after saving it, I cannot get the attributes of the Parent post object. So I have: comment.save() post.comments.add(comment) Now I have a function: @receiver(post_save, sender=Comment) def update_comment_count(sender, instance, **kwargs): cache.set("post_comment_count_{}".format(instance.post.id), instance.post.comments.all().count()) However, this will not work since the post object hasn't added the comment object yet, is there any way to fix this? -
How to make dynamic data in Javascript from Django views
I have js like this, I want make that data is dynamic from database. I want to pass that value from views. How to do that? data: [ { value: 335, name: 'Coding' }, { value: 310, name: 'Database' }, { value: 234, name: 'UIX' }, { value: 135, name: 'Manajemen' },] I try this code : cursor.execute('SELECT k.nama_ktg as name, COUNT(m.nim) as value FROM mahasiswa_mhs_si m, mata_kuliah_kategori_utama u, mata_kuliah_kategori k WHERE k.kode_ktgu_id = u.id AND m.kode_ktg_id = k.id GROUP BY k.id') ktg_mhs = cursor.fetchall() #JSON CHART result = [] chart_ktg =[ { 'value' : ktg_mhsi[1], 'name' : ktg_mhsi[0] } for ktg_mhsi in ktg_mhs ] data = json.dumps(chart_ktg) And the result is this : [{"value": 51, "name": "Coding"}, {"value": 27, "name": "Database"}, {"value": 223, "name": "UI/UX"}, {"value": 34, "name": "Manajemen"}, {"value": 7, "name": "Dasar Sistem Informasi"}, {"value": 64, "name": "Bisnis"}, {"value": 18, "name": "Kesehatan"}, {"value": 235, "name": "Lain-lain"}] -
Why delete method not allowed in django?
I have added delete method in my view but I keep getting error as below "detail": "Method \"DELETE\" not allowed." Not sure whats wrong? Can anyone help? defining delete method as this def delete(self, request): -
Django duplicate column name: Username
I'm getting the following error when I try to migrate: django.db.utils.OperationalError: duplicate column name: Username howerever I don't even have a username field -
django controlcenter url name
while using django-controlcenter package, I am trying to set a url in a html template to access a dashboard. In my urlpattersn I have: path('admin/dashboard/', controlcenter.urls, name='dashboard'), In my settings, I have a set a dashboard: CONTROLCENTER_DASHBOARDS = ( ('admindash', 'myapp.dashboards.AdminDashboard'), ) So for a url that normally resolves as /admin/dashboard/admindash , what the template url should be? django.urls include would not work with the package and the issue would be to register a proper namespace. I directly tried {% url 'dashboard:admindash' %} but it returned a NoReverseMatch error.