Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Request URL in Django error message does not correspond to the acual request url
I'm building an app with Django and Django-Rest-Framework. The frontend js application makes API calls to the backend. It works well when I test it using python manage.py ruserver but when i test it in a VM similar to my production environment, all API request get a 500 response. In the error message, the Request URL does not correspond to the actual request that was made. The actual request url looks like this: http://127.0.0.1:8080/api/account/login/ But the error message says it is something like this: http://127.0.0.1:8080/path/to/my/djoserapp/on/server/api/account/login/ The server is configured with nginx and daphne and the django version is 3.1 I don't know where to begin solving this and will greatly appreciate any help i could get. Thank you -
Javascript ID not showing reference to input text box - Django
{% extends 'halls/base.html' %} {% block content %} <div class="container"> <h2>Add Video to {{hall.title}}</h2> <form method="post"> {% csrf_token %} {% load widget_tweaks %} {% for field in form %} <div class="form-group {% if field.errors %} alert alert-danger {% endif %}"> {{ field.errors }} {{ field.label_tag }} {% render_field field class='form-control' %} </div> {% endfor %} <button type="submit" class="btn btn-primary"> Add</button> </form> <br> <h2>OR</h2> <form> {% for field in search_form %} <div class="form-group "> {{ field.errors }} {{ field.label_tag }} {% render_field field class='form-control' %} </div> {% endfor %} </form> <div id="search_results"></div> <script type="text/javascript"> var delayTimer; $("#id_search_term").keyup(function (){ clearTimeout(delayTimer); $('#search_results').text('Loadingggg'); }); </script> </div> {% endblock %} this is the HTML code. SO basically the whole idea here is when I inspect the search_form, it should give the id of the input box as "id_search_term". But when I inspect the box, it gives as id="id_search". I am not able to find a way to reference the input box with the ID in the script tag -
Django and Time Zones, database storing in UTC but writing regular python to try to make a daily report failing
I have this database that is tracking logins and logouts on a site (contact tracing woo hoo) when they login via the form or a qr code, it stamps the right date. Well sort of, the form works caues they can put in the date and time exactly. The QR code that time stamps is one hour off of local time (I am not sure why). This is fine, and inside the database all the dates are in UTC, which Django works translating the data back out when I display it somehow...so I am fine with this. The problem is I am writing a reporting python script not using django but contacting the same database. I want to cron job an email out at 11:55pm every night of the logins and log outs for the day, though by 11:55pm local time is like 5:55am UTC the next day, of which there is never any logins and logouts so the report is always empty. I lost the automagic of django in the interrigation of this database...so I am not sure what I can do to get the right data from the database. My report function is simple here: import sqlite3 def … -
I'm new at cron and scrapy. // cron not working in AWS. (it's fine in my local environment)
In AWS, source /home/ubuntu/envv/bin/activate && cd /srv/MyFirstCrawler/scraper && scrapy crawl blondieshop_spider my virtualenv is envv, my project is scrapy + django, project name is MyFirstCrawler, above cron is working when i type in command line. but not working in cron.. when i typed 'service cron status' Sep 21 05:01:01 ip-172-31-5-186 CRON[6473]: pam_unix(cron:session): session opened for user ubuntu by (uid=0) Sep 21 05:01:01 ip-172-31-5-186 CRON[6474]: (ubuntu) CMD (source /home/ubuntu/envv/bin/activate && cd /srv/MyFirstCrawler/scraper && scrapy crawl blondieshop_spider) Sep 21 05:01:01 ip-172-31-5-186 CRON[6473]: pam_unix(cron:session): session closed for user ubuntu i really can't figure out what's wrong. -
Django ImportError : cannot import name 'Manager' from partially initialized module '..\django\db\models\__init__.py'
Looked for the solutions and found that it may be the case of circular import. But I'm having simple imports, leaving no space for such a case. models.py from django.db import models forms.py from django import forms from FeedbackApp.models import StudentDetails views.py from django.shortcuts import render, redirect from django.urls import reverse from FeedbackApp.forms import LoginForm only simple model class having some fields, ModelForm from that model , and view for that form (myvenv) G:\projects\pycharmproj\Feedback>python manage.py runserver Traceback (most recent call last): File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\core\ma autoreload.check_errors(django.setup)() File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\utils\a fn(*args, **kwargs) File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\__init_ from django.urls import set_script_prefix File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\urls\__ from .base import ( File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\urls\ba from .exceptions import NoReverseMatch, Resolver404 File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\urls\ex from django.http import Http404 File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\http\__ from django.http.response import ( File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\http\re from django.core.serializers.json import DjangoJSONEncoder File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\core\se from django.core.serializers.base import SerializerDoesNotExist File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\core\se from django.db import models File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\db\mode from django.db.models.base import DEFERRED, Model # isort:skip File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\db\mode from django.db.models.options import Options File "G:\projects\pycharmproj\Feedback\myvenv\lib\site-packages\django\db\mode from django.db.models import AutoField, Manager, OrderWrt, UniqueConstraint ImportError: cannot import name 'Manager' from partially initialized module 'dja ackages\django\db\models\__init__.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) … -
I want to authenticate user name and password in sanic using djnago tables
from django.contrib.auth import authenticate user = authenticate(username='john', password='john@122') if user is not None: # A backend authenticated the credentials else: # No backend authenticated the credentials Here I wan't to authenticate user name and password in sanic instead of django. Don't want to install django in sanic. but wan't to authenticate and create password and set to database. Is there any library to get my work done? or how can I create a normal password to djnag hashed password and authenticate? -
DoesNotExist on django
Could somebody help please? I try to play videos on my site but it sems I have some problem. I am a beginner in python and django. Here is what showed to me: (Thank you in further). ['DoesNotExist', 'MultipleObjectsReturned', 'class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'getstate', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'setstate', 'sizeof', 'str', 'subclasshook', 'weakref', '_check_column_name_clashes', '_check_constraints', '_check_field_name_clashes', '_check_fields', '_check_id_field', '_check_index_together', '_check_indexes', '_check_local_fields', '_check_long_column_names', '_check_m2m_through_same_relationship', '_check_managers', '_check_model', '_check_model_name_db_lookup_clashes', '_check_ordering', '_check_property_name_related_field_accessor_clashes', '_check_single_primary_key', '_check_swappable', '_check_unique_together', '_do_insert', '_do_update', '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val', '_state', 'check', 'clean', 'clean_fields', 'comment_set', 'date_error_message', 'datetime', 'delete', 'description', 'from_db', 'full_clean', 'get_deferred_fields', 'get_next_by_datetime', 'get_previous_by_datetime', 'id', 'objects', 'path', 'pk', 'prepare_database_save', 'refresh_from_db', 'save', 'save_base', 'serializable_value', 'title', 'unique_error_message', 'user', 'user_id', 'validate_unique'] XZZ4ROG1UHRoute_Montélimar.mp4 user signed in <QuerySet []> [21/Sep/2020 06:11:43] "GET /video/24 HTTP/1.1" 200 966 -
How to display Date in popup Modal in Django?
I want to display data in the popup, I have a list on products but when a user clicks on the product id then it should be open in popup according to that product id. here is my views.py file... def myview(request): datas=TestForm.objects.all template_name='test.html' context={'datas':datas} return render(request, template_name, context) def myview(request, id): display=TestForm.objects.get(pk=id) template_name='test.html' context={'display':display} return render(request, template_name, context) here is my test.html file... <button type="button" class="btn btn-primary" data-toggle="modal" data- target="#exampleModal"> {{data.product_id}} </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria- labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <tr> <td>{{data.name}}</td> <td>{{data.price}}</td> <td>{{data.category}}</td> </tr> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> Currently, it's displaying only the first product on click all products id's, Please let me know how it can display product data according to click product id. -
django app with ajax for processing dataframe
I am trying to show busy indicator image as soon as the user uploads an excel file . While the file process is done, I would like to replace the image with processed table. Problem: The ajax success block is not executing(alert message inside success block is not working) The uploaded data is converted to json but unable to convert back to dataframe for processing. The code that gets executed on upload button click in views.py def indicator(request): excel_file = request.FILES["excel_file"] uploaded_data = pd.read_excel(excel_file) df_json = uploaded_data.to_json() return render(request,'myapp/indicator.html',{'df':df_json}) indicator.html: <script> var dataframe = JSON.parse("{{df|escapejs}}"); var replace_data = function(data){ alert('successs') $('#success').append(data.list_of_jsonstuffs); $('#loading').remove() } $(document).ready(function(){ $.ajax({ url: '/processing/', type:'GET', dataType: 'json', data: JSON.stringify(dataframe), success: function(data){ alert('ajax done') replace_data(data) } }) }) </script> The function in view that triggers and does the processing. @csrf_exempt def processing_file(request): if request.is_ajax(): excel_file1 = json.dumps(request.GET) e1 = json.loads(excel_file1) input_df = pd.DataFrame.from_dict([e1]) print(input_df.shape) processed = gen.generate_output_columns(excel_file) output_validation = processed[const.OUTPUTCOLUMNSWITHVALIDATION] excel_data = output_validation.values.tolist() return excel_data The input_df is 1 by 2 however uploaded excel is 17 by 55. Somewhere in JSON Stringify and json loads the structure is getting changed but when I try with POST I was once able to succeed with processing but success block never … -
django file upload is not working in azure blob with new version
After updated the azure blob version, it won't install everything. It will install specific version of namespace in the blob. So i installed the following packages. azure-common==1.1.25 azure-core==1.8.1 azure-nspkg==3.0.2 azure-storage-blob==12.4.0 i'm not able to upload the blob. All the references in the SO and other platforms are for old versions. For new versions there is no reference. The error i'm getting is from azure.storage.blob import BlobPermissions, ContentSettings ImportError: cannot import name 'BlobPermissions' from 'azure.storage.blob' if i manually went to the path and removed the BlobPermissions from import compilation is happening. But upload is not happening, upload time i'm getting this error connection_string=self.connection_string) endpoint_suffix=self.endpoint_suffix) TypeError: __init__() got an unexpected keyword argument 'token_credential' Can anyone help me with proper doc for django azure upload with new version. The references i got in SO is manual upload way. Some reference i got in SO: Upload and Delete Azure Storage Blob using azure-storage-blob or azure-storage ImportError: cannot import name 'BlobService' when using Azure Backend -
ImportError running multiple test modules w/ manage.py test
Presently I'm testing only one app for which I have nested a package dedicated to separating my tests (test_models.py, test_forms.py, etc.). When I created the test_forms.py module and attempted to run python manage.py test, the following error is raised: ImportError: Failed to import test module: photos.test.test_forms Traceback (most recent call last): File "C:\..\..\..\..\..\Python\Python37\lib\unittest\loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "C:\..\..\..\..\..\Python\Python37\lib\unittest\loader.py", line 377, in _get_module_from_name __import__(name) File "C:\..\..\..\..\..\django_photo_app\photos\test\test_forms.py", line 2,in <module> from ..forms import PhotoForm File "C:\..\..\..\..\..\django_photo_app\photos\form.py", line 8, in <module> from ..models import Photo ValueError: attempted relative import beyond top-level package The import triggering this error is: from ..forms import PhotoForm When I remove any reference to that form in the test module the overall tests run fine. Prior to creating test_forms.py , there was only the test_models.py module and there was no problem running the tests. Why is it that Django raises an ImportError and then a subsequent ValueError in this manner when running python manage.py test? -
trying to submit a java form to an API
here is my js code that am trying to run , in this js function that sends an email to this API '/emails' the form takes recipients , subject and body as inputs .. i have no idea what went wrong because the code makes sense to me , someone told me this issue is due to the usage of multiple languages but am not using any (am on the latest version of django python and VScode) : function sendEmail() { const recipients = document.querySelector('#compose-recipients').value; const subject = document.querySelector('#compose-subject').value; const body = document.querySelector('#compose-body').value; console.log(recipients); fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: recipients, subject: subject, body: body }) }) .then(response => response.json()) .then(result => { if ("message" in result) { // The email was sent successfully! load_mailbox('sent'); } if ("error" in result) { // There was an error in sending the email // Display the error next to the "To:" document.querySelector('#to-text-error-message').innerHTML = result['error'] } console.log(result); console.log("message" in result); console.log("error" in result); }) .catch(error => { // we hope this code is never executed, but who knows? console.log(error); }); return false; } and here is my error : Exception happened during processing of request from ('127.0.0.1', 54200) Traceback (most recent call last): … -
How can I get Django to ignore an old migration it thinks hasn't been applied?
Somehow, our test DB's migration history looks like this: ... [X] 0034_timestamp_fields [X] 0035_password_history [ ] 0036_login_lockout (2 squashed migrations) [X] 0037_force_password_change ... We're now up to migration 67; this is ancient history. Now there is a new migration, 68, that I'd like to apply. If I try to migrate right now, I get a "relation already exists" error on migration 36. I tried specifically migrating up to 67 with --fake, but got "No migrations to apply." So.. how can convince Django that 36 is already applied? Or just get it to ignore it for now and apply 68 without worrying about it? This is Django 1.11.26. -
How to resolve Undefined Table error in Django
I am new to django , was following a tutorial on youtube, on how to create custom user model. This is my model from django.db import models #from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser , BaseUserManager # Create your models here. class AccountManager(BaseUserManager): def create_user(self, email,firstName,lastName,m_phone): if not email: raise ValueError('Email Id is a required Field') if not firstName: raise ValueError('First name is a required Field') if not lastName: raise ValueError('Last name is a required Field') if not m_phone: raise ValueError('Mobile Ph. no is a required Field') user = self.model(email=self.normalize_email(email), firstName=firstName, lastName = lastName, m_phone = m_phone) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email,firstName,lastName,m_phone,password): user = self.create_user(email=self.normalize_email(email), firstName=firstName, lastName = lastName, m_phone = m_phone, password = password) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(unique=True) firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) m_phone = models.CharField(max_length=50) l_phone = models.CharField(max_length=50) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['firstname','lastname','m_phone'] objects = AccountManager() def __str__(self): return self.firstName def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self,app_label): return True # class Profile(models.Model): # user = models.OneToOneField(Account, on_delete = models.CASCADE) # profilePicture … -
How can I deserialize multiple files and form data in a single request using Django Rest Framework?
I would like to desearialize a form with some basic form data + one or more uploaded files. If I send the following request (generated as Python Requests code using Postman) import requests url = "http://127.0.0.1:8000/forms/test/" payload = { 'customer_id': '123456789', 'customer_name': 'Billy Bob'} files = [ ('files', open('/C:/tmp/aaaaa.csv','rb')), ('files', open('/C:/tmp/bbbbb.csv','rb')) ] headers= {} response = requests.request("POST", url, headers=headers, data = payload, files = files) print(response.text.encode('utf8')) The code returns the following response (I hoped it would save the file instead). { "files": [ "This field is required." ] } Models class Mtfar(models.Model): date = models.DateTimeField(auto_now_add=True) customer_id = models.IntegerField() customer_name = models.CharField(max_length=254) class MtfarFile(models.Model): file = models.FileField(blank=False, null=False) mtfar = models.ForeignKey(Mtfar, related_name='files', on_delete=models.CASCADE) Serializers class MtfarFileSerializer(serializers.ModelSerializer): class Meta: model = MtfarFile fields = ['file'] class MtfarSerializer(serializers.ModelSerializer): files = MtfarFileSerializer(many=True) class Meta: model = Mtfar fields = ['customer_ptid', 'customer_name', 'files'] View @api_view(['POST']) @parser_classes([MultiPartParser]) def post_generic_form(request): data = request.data filelist = [] for f in request.FILES.getlist('files'): filelist.append({ 'file': f }) data.setlist('files', filelist) serializer = MtfarSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Use pgadmin4 to open existing Django project DB
I have deployed a Django project in ptyhon venv in CentOS 8. Evertything wokrking fine. Now I'd like to install pgadmin4 to check detail data inside PostreSQL. After installation by official site instruction, pdadmin page seems working. I can also login as default user (postgres) But there's no any server showing up in left menu. Maybe I missed some steps? Pls kindly help, thx! -
Twilio outbound call hold disconnecting callee
I am implementing hold function in Twilio. Whenever I call the hold function, the callee is getting disconnected. The code below only applies to the caller, not the callee. if call_sid: client = Client(self.account_sid, self.auth_token) twiml_string = """ <Response> <Enqueue>xx</Enqueue> </Response> """ client.calls(call_sid).update(method="POST", twiml=twiml_string) -
There was an error in the distribution of the DjangoProject in PythonAnywhere - ModuleNotFoundError: No module named 'mysite'
There is an error in distribution / pythonanywhere , django_project/ I looked up all the related Stack Overflow articles! but i didn't solve this problem please let me know please let me know please let me know please let me know please let me know 2020-09-21 02:01:37,406: Error running WSGI application 2020-09-21 02:01:37,407: ModuleNotFoundError: No module named 'mysite' 2020-09-21 02:01:37,407: File "/var/www/emoclew_pythonanywhere_com_wsgi.py", line 12, in <module> 2020-09-21 02:01:37,407: application = StaticFilesHandler(get_wsgi_application()) 2020-09-21 02:01:37,407: 2020-09-21 02:01:37,407: File "/home/emoclew/covid19_survey/myvenv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-09-21 02:01:37,407: django.setup(set_prefix=False) 2020-09-21 02:01:37,408: 2020-09-21 02:01:37,408: File "/home/emoclew/covid19_survey/myvenv/lib/python3.8/site-packages/django/__init__.py", line 19, in setup 2020-09-21 02:01:37,408: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2020-09-21 02:01:37,408: 2020-09-21 02:01:37,408: File "/home/emoclew/covid19_survey/myvenv/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ 2020-09-21 02:01:37,408: self._setup(name) 2020-09-21 02:01:37,409: 2020-09-21 02:01:37,409: File "/home/emoclew/covid19_survey/myvenv/lib/python3.8/site-packages/django/conf/__init__.py", line 70, in _setup 2020-09-21 02:01:37,409: self._wrapped = Settings(settings_module) 2020-09-21 02:01:37,409: 2020-09-21 02:01:37,409: File "/home/emoclew/covid19_survey/myvenv/lib/python3.8/site-packages/django/conf/__init__.py", line 177, in __init__ 2020-09-21 02:01:37,409: mod = importlib.import_module(self.SETTINGS_MODULE) it is my project tree (myvenv) 02:06 ~/covid19_survey (master)$ tree . ├── db.sqlite3 ├── firstProject │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── ido │ ├── __init__.py │ ├── __pycache__ │ │ … -
Media files not serving Django production
I built an app using Django with PostgreSQL as a database. After I finished it, I decided to deploy it on Heroku. Their documentation was too complex for me to understand, so I went to this post on Medium and did what they said. A Server Error (500) came in my application, and I found out that I removed the line STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' it worked properly when I ran python manage.py runserver on my local machine, but it doesn't serve the media files. After I pushed it to Heroku, it still shows a Server Error (500) there. I am showing few parts of my code. Could you please tell me how I could serve the media files properly and why the server error is coming only in the Heroku run app? If you need any code other than whatt I have given here, please inform me in the comments. I know that you can't serve media files when DEBUG = False and that you should use Nginx, but please tell me where I can find a good guide for Nginx deployment on Heruko. Thanks in advance. settings.py """ Django settings for btre project. Generated by 'django-admin startproject' using Django … -
Use external webpage to obtain JWToken for use by Django REST
Suppose you've got a Django REST server that has authentication setup. There are users, groups, permissions, etc. Now, suppose you want to enable a user to: access one of the REST endpoints have Django REST recognize that the user did not provide a JWToken in the AUTHENTICATION cookie redirect to an external page, and include the current URL, say www.getmyjwtoken.com/?redirect_back=www.mydjangorestserver.com/foo/bar/baz/1, and then read the AUTHENTICATION cookie from the result after the mydjangorestserver returns the user back to foo/bar/baz/1 with the cookie in hand. How do you go about enabling (1), (2) and (3)? That is, once the cookie is there, you already know how to read it (Step 4). How do you instruct Django to reference this external webpage to produce the JWT? -
Django-Plotly-Dash retrieving URL slug
I want to include plotly-dash within a Django framework. I want to have one app incorporated into one HTML template that will present line graphs read as pandas dataframe from csv based on the slug entered in the url. The csv files share the same name as the slug to make them easy (I thought) to open. I want to be able to pull the url path, or the slug, and use that to determine which csv file my app opens and uses to present the data for the line plot. This worked fine with only Dash. I could use the url and pathname in the callback and use the pathname as the name of the csv file and have the app dynamically open the proper csv file based on the url slug. @app.callback( Output('indicator-graphic', 'figure'), [Input('url', 'pathname'),]) def update_graph(pathname): df=pd.read_csv('path/to/file/'+pathname+'.csv) The above code worked fine in the Dash test server. When I incorporate this into Django, the url and pathname won't work anymore. I have tried everything I can think of to pass the slug or pathname as an Input to the Dash callback. I cannot get anything to work. Then, I tried to set the dataframe as global … -
How to implement a simple "like" feature in Django REST Framework?
I'm a beginner building the backend API for a social media clone using DRF. The frontend will be built later and not in Django. I'm currently using Postman to interact with the API. I'm trying to implement a "like" feature as you would have on Facebook or Instagram. I cannot send the correct data with Postman to update the fields which bear the many-to-many relationship. Here is some of my code: models.py class User(AbstractUser): liked_haikus = models.ManyToManyField('Haiku', through='Likes') pass class Haiku(models.Model): user = models.ForeignKey(User, related_name='haikus', on_delete=models.CASCADE) body = models.CharField(max_length=255) liked_by = models.ManyToManyField('User', through='Likes') created_at = models.DateTimeField(auto_now_add=True) class Likes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) haiku = models.ForeignKey(Haiku, on_delete=models.CASCADE) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password', 'url', 'liked_haikus'] extra_kwargs = { 'password' : {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() token = Token.objects.create(user=user) return user class HaikuSerializer(serializers.ModelSerializer): class Meta: model = Haiku fields = ['user', 'body', 'liked_by', 'created_at'] class LikesSerializer(serializers.ModelSerializer): model = Likes fields = ['haiku_id', 'user_id'] views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] @action(detail=True, methods=['get']) def haikus(self, request, pk=None): user = self.get_object() serializer = serializers.HaikuSerializer(user.haikus.all(), many=True) return Response(serializer.data) class UserCreateViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer … -
Django template does not exist @
I am using python 3.7.2 and Django 2.1 and every time I try to load the home url I get the following error. TemplateDoesNotExist at / ghostwriters/post_list.html Request Method: GET Request URL: http://localhost:8080/ Django Version: 2.1 Exception Type: TemplateDoesNotExist Exception Value: ghostwriters/post_list.html Exception Location: C:\Users\User.virtualenvs\ghostwriter-HT06mH6q\lib\site-packages\django\template\loader.py in select_template, line 47 Python Executable: C:\Users\User.virtualenvs\ghostwriter-HT06mH6q\Scripts\python.exe Doesn't make any sense because there really is no post_list.html and its not in my app level urls.py or my views.py so why is this happening? urls.py: from django.urls import path from .views import PostListView urlpatterns = [ path('', PostListView.as_view(), name='home'), ] views.py: from django.shortcuts import render from django.views.generic import ListView from .models import Post class PostListView(ListView): model = Post template = 'home.html' settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, -
NoReverseMatch at /videos/list/ Reverse for 'list_videos' not found. 'list_videos' is not a valid view function or pattern name
Well I am trying to create a Playlist quite similar with YouTube. But the Playlist can only create by superuser from admin panel and other user can only see that playlist and the videos within the playlist. When I thought that I am done than suddenly this error occured. I don't know where I am making mistake. Please help me to fix this problem. videos/models.py class VideosList(models.Model): list_title = models.CharField(max_length=255) list_cover = models.ImageField(upload_to='list cover', height_field=None, width_field=None, max_length=None,blank =True) create_date = models.DateField(default = timezone.now) def __str__(self): return self.list_title class VideosModel(models.Model): videos_lists = models.ForeignKey(VideosList,on_delete=models.CASCADE) video_title = models.CharField(max_length=250) video_url = models.URLField(max_length=1200) video_discription = models.TextField() create_date = models.DateField(default = timezone.now) def __str__(self): return self.video_title videos/views.py class VideosListView(ListView): model = VideosList context_object_name = 'videos_lists' template_name = "videos/videos_lists.html" def get_queryset(self): return VideosList.objects.filter(create_date__lte=timezone.now()).order_by('-create_date') class VideosModelListView(ListView): model = VideosModel template_name = "videos/list_videos.html" context_object_name = 'videos_list' def get_queryset(self,*args, **kwargs): videoslist = get_object_or_404(VideosList, list_title=self.kwargs.get('list_title')) return VideosModel.objects.filter(videos_lists=videoslist).order_by('-create_date') videos/urls.py app_name = 'videos' urlpatterns = [ path('list/',views.VideosListView.as_view(),name ='videos_playlist'), path('list/<str:list_title>/',views.VideosModelListView.as_view(),name ='list_videos'), ] videos/videos_list.html {% extends 'pages/videos.html' %} {% block content %} {% for all_lists in videos_lists %} <p style='text-align:center'><img src="{{ all_lists.list_cover.url }}" alt="No cover" height="450px" width="550px" ></p> #This h2 line generating error and I dont know how to fix it. <h2 style='text-align:center'>Title :<a href="{% … -
How to remove a many to many model field's instance from a particular model in Django
I have an e-learning website where students can enroll into courses and access contents within courses created are created and managed by instructors. But i don't how to make students unenroll from a particular course and then update the course list after unenrolling from a course. Note that the course model has a many to many model field to students. Here's the models.py file of courses app :- class Course(models.Model): owner = models.ForeignKey(User, related_name='courses_created', on_delete=models.CASCADE) subject = models.ForeignKey(Subject, related_name='courses', on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) overview = models.TextField() created = models.DateTimeField(auto_now_add=True) students = models.ManyToManyField(User,related_name='courses_joined',blank=True) class Meta: ordering = ['-created'] def __str__(self): return self.title class StudentRegistrationView(CreateView): template_name = 'students/student/registration.html' form_class = UserCreationForm success_url = reverse_lazy('homepage') def form_valid(self, form): result = super(StudentRegistrationView, self).form_valid(form) cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['password1']) login(self.request, user) return result Here are the student views in students app:- class StudentEnrollCourseView(LoginRequiredMixin, FormView): course = None form_class = CourseEnrollForm def form_valid(self, form): self.course = form.cleaned_data['course'] self.course.students.add(self.request.user) my_group = Group.objects.get(name='Enrolled') my_group.user_set.add(self.request.user) return super(StudentEnrollCourseView, self).form_valid(form) def get_success_url(self): return reverse_lazy('student_course_detail', args=[self.course.id]) class StudentCourseListView(LoginRequiredMixin, ListView): model = Course template_name = 'students/course/list.html' def get_queryset(self): qs = super(StudentCourseListView, self).get_queryset() return qs.filter(students__in=[self.request.user])