Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Synchronize Django DB with Ionic Client
I have a model in my django project hosted on Google Cloud Projects. Which looks like the one below. class License(models.Model): PLATFORM_CHOICES = ( ("ios", "iOS"), ("android", "Android"), ) LICENSE_CHOICES = ( ("prod", "Production"), ("dev", "Development"), ) license = models.TextField() created_dt = models.DateTimeField(auto_now_add=True) expiration_dt = models.DateTimeField() license_type = models.CharField(max_length=11, choices=LICENSE_CHOICES) platform_type = models.CharField(max_length=7, choices=PLATFORM_CHOICES) I am using this model with a serializer to retrieve the data using an Ionic+Angular client. This license is used to activate a service, and this licenses change every X days. I do not want to check on every request whether the key is not expired or fetch the key everytime the service is being used. I want to save this key on local storage, and save automatically on local storage every time a new value is created or updated in the database. How can I make this possible? I am trying to avoid to do something like this: this.sharedService.getLicense().subscribe(licenses => { var todaysDate = new Date(); licenses.map(license => { if (this.platform.is('ios') && todaysDate <= new Date(license.expiration_dt)) { this.licenseKey = license; } }); }) Any ideas will be much appreciated. -
Django Rest Framework Datatables DELETE
Issue I would like to send a list of ID's to the Django Rest Framework API url (which is the rest_framework routers default). So far everything is working up to the point of sending the ID's. When I click the delete button the DELETE call goes to 127.0.0.1:8000/api/entries/_id_/ and does not add the proper ID's that are selected for deletion. Error Message From Server I'm sure this was more or less obvious: {detail: "Not found."} detail: "Not found." entry_list.html {% extends "dashboard/base.html" %} {% load i18n %} {% block content %} <style> table.dataTable tbody tr.odd.selected { background-color:#acbad4 } table.dataTable tbody tr.even.selected { background-color:#acbad5 } </style> <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h2 class="text-gray-800">{% block title %}{% trans "Imported Entries" %}{% endblock %}</h2> <a role="button" class="btn btn-success" href="{% url 'import' %}"><i class="fas fa-plus-circle"></i> Import New Entires</a> </div> <button id="countbutton">Count rows</button> <button id="deletebutton">Delete rows</button> <!-- Content Row --> <div class="row"> <div class="col-md-12"> <table id="entrytable" class="table-hover table display table-bordered" align="center" style="width:100%"> <thead> <tr role="row"> <th>id</th> <th>date</th> <th>amount</th> <th>price</th> <th>fee</th> <th>entry_type</th> <th>reg_fee</th> <th>transaction_id</th> <th>trade</th> <th>symbol</th> <!-- <th>created_by</th>--> </tr> </thead> </table> </div> </div> {% endblock %} {% block js %} <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css"/> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/dataTables.bootstrap4.min.css"/> <!--https://datatables.net/examples/server_side/select_rows.html--> <!--<link rel="stylesheet" type="text/css" … -
Django Websockets Data going to the wrong Socket
Using Django Websockets + Channels, I create a (One) group and the message back and forth works just fine. Lets call this Group A The problem starts when I open a SECOND group and a SECOND (Lets call this group B) WebSocket connection in a different browser. The messages that I am trying to send to group A (first WebSocket connection), are going to group B (second WebSocket connection). All the messages that belong to group A go to the second WebSocket and the group B messages also go to the second socket. Here's my consumer.py import json from asgiref.sync import async_to_sync import logging LOG = logging.getLogger(__name__) from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer class EventConsumer(AsyncWebsocketConsumer): async def connect(self): self.id = self.scope['url_route']['kwargs']['id'] self.group_name = f'enl_events_log_{self.id}' # Join room group await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): # text_data_json = json.loads(text_data) # message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.group_name, { 'type': 'send.message', 'message': "Message received" } ) # Receive message from room group async def send_message(self, event): message = event['message'] # Send message to WebSocket await … -
how to send and retrive image in django with ajax?
I need to upload an image in the server without using the django models.and also i needs to do with the help of ajax. My html code: <form id='imform' action="#" method="GET" role="form" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="img" multiple> <input type="submit" value='submit'> </form> My ajax code: $("#imform").submit(function (event) { event.preventDefault() var idata=new FormData(); idata.append('one','one'); console.log(idata['one']); $.ajax({ type:'GET', url: 'imageupload', data:{ one:'one', img:idata, }, contentType:false, success: function (e) { console.log('success') }, }); }); In views.py: def imageupload(req): ???????????? How to get the image in the function?Is there any way to get the image and save in a specific folder in the server. -
I want to run my django app from my own computer's server. How can I do that?
Suppose my public IP address is x.x.x.x.x If I want to access my django app with that IP address how can I do that? -
Not able to add value to Foreign Key using Django models
I have created 2 models, Customer and Room. class Customer(models.Model): firstname = models.CharField(max_length=15) lastname = models.CharField(max_length=15) age = models.IntegerField() sex = models.CharField(max_length=10) phoneno = models.IntegerField() emailid = models.CharField(max_length=25) address = models.CharField(max_length=50) children = models.IntegerField() adults = models.IntegerField() roomtype = models.CharField(max_length=10) aadharno = models.CharField(max_length=15) roomno = models.OneToOneField(Room,on_delete=models.CASCADE) daysstayed = models.IntegerField() date_visited = models.DateTimeField(default=timezone.now) emp_id = models.ForeignKey(Employee,on_delete=models.SET_NULL,blank=True,null=True) class Room(models.Model): roomno=models.IntegerField(default=0) roomtype=models.CharField(max_length=15) vacancy=models.BooleanField(default=False) current_user=models.OneToOneField('customer.Customer',on_delete=models.SET_NULL,blank=True,null=True) I am using the following code to insert values in the Customer model. customer = Customer(firstname=firstname,lastname=lastname,age=age,emailid=emailid,address=address,phoneno=phoneno,children=children, adults=adults,roomtype=roomtype,aadharno=aadharno,daysstayed=daysstayed,sex=sex,roomno=i.roomno.id) customer.save() All the values are obtained using a form except for roomno. I get the following error when i use roomno=i.roomno.id 'int' object has no attribute 'id' when i use roomno=i.id I get the error Cannot assign "7": "Customer.roomno" must be a "Room" instance. where i is an instance of room and 7 is the value to be added. -
Django: Annotate with field from another table (one-to-many)
Good day. I wish to annotate my model with information from a different table. class CompetitionTeam(models.Model): competition_id = models.ForeignKey('Competition', on_delete=models.CASCADE, to_field='id', db_column='competition_id') team_id = models.ForeignKey('Team', on_delete=models.CASCADE, to_field='id', null=True, db_column='team_id') ... class Team(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) teamleader_id = models.ForeignKey('User', on_delete=models.CASCADE, to_field='id', db_column='teamleader_id') ... class Competition(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) ... Looping through my competitions, I wish to retrieve the list of competitionteam objects to be displayed with the relevant team's name. I tried: CompetitionTeam.objects.filter(competition_id=_competition.id).filter(team_id__in=joined_team_ids).annotate(name=...) -where instead of the ellipses I put Subquery expressions in. However, I'm unsure of how to match the team_id variable. eg. *.anotate(name=Subquery(Team.objects.filter(id=competitionteam.team_id)).values('name')) Related is the question: Django annotate field value from another model but I am unsure of how to implement that in this case. In that case, in place of mymodel_id, I used team_id but it only had parameters from the Team object, not my competition team object. I didn't really understand OuterRef but here is my attempt that failed: CompetitionTeam.objects.filter(competition_id=_competition.id).filter(team_id__in=joined_team_ids).annotate(name=Subquery(Team.objects.get(id=OuterRef('team_id')))) "Error: This queryset contains a reference to an outer query and may only be used in a subquery." -
Installation failed of resume-parser 0.6 Package in system
I tried to install this package but it didn't install on my system. Then trying from virtual environment but same things happen. -
Group object has no attribute user_set
I'm using a custom User created with AbstractBaseUser and I tried to add users to a specific group using the django admin. But there were no option to add users to a group. So I found a solution from the stack overflow and It gave me the capability to add users to the group I created. But after saving the user It gives me an error saying Group object has no attribute user_set My User Model class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have an username") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=80, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=100,null=True) last_name = models.CharField(max_length=100,null=True) phone_no = models.CharField(max_length=12,null=True) date_joined = models.DateField( verbose_name='date joined', auto_now_add=True) last_login = models.DateField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return … -
How Do I Undo Some Bad Architecture In Order To Avoid Circular Import
I have posted the similar question previously due to this circular import issue: ERROR: api.serializers (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: api.serializers Traceback (most recent call last): File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) File "/Users/nick/work/shiftwork_backend/api/serializers/__init__.py", line 1, in <module> from .default import * File "/Users/nick/work/shiftwork_backend/api/serializers/default.py", line 10, in <module> from api import views File "/Users/nick/work/shiftwork_backend/api/views/__init__.py", line 1, in <module> from .base import * File "/Users/nick/work/shiftwork_backend/api/views/base.py", line 10, in <module> from api.serializers import ConfigSerializer ImportError: cannot import name 'ConfigSerializer' from partially initialized module 'api.serializers' (most likely due to a circular import) (/Users/nick/work/shiftwork_backend/api/serializers/__init__.py) And I got some comments. Most of them did not work at the end so I started paying attention to the one that pointed out some architectural flaws, thanks to Klaus D. Look, at the traceback, your import goes: serializers → serializers.default → views → views.base → serializers. You have to break that circle by reorganizing imports or restructuring your code. – Klaus D. So I was trying to figure out how to break this circular import chain. First thing I did was look for some hints online. Such as this: Can't import serializer from other serializer … -
How to remove Extra dots from Django-filters?
I am filtering data using django-filters, but i am getting an extra dots in my dropdown, Please let me know How I can remove that Extra dots from my dropdown filters, I want to give the lable there but I am unable to do that, Please check my code and let me know How I can solve thsi issue. here is my filters.py file... class MyFilter(django_filters.FilterSet): type = django_filters.ChoiceFilter(choices=Data_TYPE, field_name='data_type') class Meta: model = Project fields = ['category', 'type'] here is my test.html file where I am displaying the filters in dropdown... <form method="GET" action=""> <div class="dropdown bootstrap-select hero__form-input form-control custom-select"> {% render_field projectlist.form.category|attr:"type:select" class="hero__form-input form-control custom-select" onchange="this.form.submit()" %} </div> <div class="dropdown bootstrap-select hero__form-input form-control custom-select"> {% render_field projectlist.form.type|attr:"type:select" class="hero__form-input form-control custom-select" onchange="this.form.submit()" %} </div> </form> here is the image, where iwant to remove the dots and i want to replace with filter lable... Plase check this https://prnt.sc/vkif04 -
DRF serializers, different field type
Is it possible to archive such situations using drf serializers, when field can be different type. I'm using such API, and field positions can be both dict or list, depends on content. How the serializer should look like. I've tried something like class PositionCreateSerializer(SapPositionSerializer): positions = serializers.ReadOnlyField(required=False) but it doesn't work -
How do I take a variable from views.py in Django and display it on my HTML page
I'm new to Django and need help with views.py. I'm trying to call on a variable from views.py on my HTML template but have no idea how to do so. The following is my views.py function: def scheduleAlgo(request): givenData=pd.read_csv('~\OneDrive\Desktop\example.csv') df = pd.DataFrame(givenData) df['Mean']=df.mean(axis=1) df = df.sort_values(by="Mean", ascending=False) df.set_index("Subject", inplace = True) firstSubject = df.index[0] secondSubject = df.index[1] thirdSubject = df.index[2] fourthSubject = df.index[3] fifthSubject = df['Mean'].idxmin() if fifthSubject==fourthSubject: fourthSubject=df.index[4] subjectList=[fifthSubject,fourthSubject,thirdSubject,secondSubject,firstSubject] subjectSelection = random.choices(subjectList, weights=(20,18,17,16,15),k=5) return render(request, 'main/testml.html', { 'firstItem': subjectSelection[0], 'secondItem':subjectSelection[1], 'thirdItem':subjectSelection[2], 'fourthItem':subjectSelection[3], 'fifthItem':subjectSelection[4], }) #assigning values for calling in template And this is my HTML code: <table> <tr> <td>{{ firstItem }}</td> </tr> </table> Also, my urls.py: path("testml", views.scheduleAlgo, name="scheduleAlgo"), I'm quite sure the function itself works since I tested it out on an iPython notebook. Essentially, I want to be able to call an index from the list (subjectSelection) and display it in my HTML code. How do I go about doing this? -
Question an about ''django dropbox'' static upload error occur " cStringIO "
I follow as https://pypi.org/project/django-dropbox-storage/; when create model class and set the dropbox error occur in cStringIO; so how to do and upload? Model.py import io from io import StringIO from cStringIO import StringIO from django.db import models from django_dropbox_storage.storage import DropboxStorage store = DropboxStorage() class Brands(models.Model): Brand_Name = models.CharField(max_length=100) photo = models.ImageField(upload_to='photos', storage=store) Error traceback C:\Users\user\Documents\django\go\go\db\models.py changed, reloading. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\user\appdata\local\programs\python\python39\lib\threading.py", line 950, in _bootstrap_inner self.run() File "c:\users\user\appdata\local\programs\python\python39\lib\threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "C:\Users\user\Documents\django\go\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\user\Documents\django\go\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\user\Documents\django\go\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\user\Documents\django\go\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\user\Documents\django\go\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\user\Documents\django\go\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\Documents\django\go\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\user\Documents\django\go\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) 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 File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in … -
How to save() an argument in a Django Model
I am learning Django, and I decided to simulate an ATM. When I run, my code works, and it says that the deposit to the Card was successful, but it does not save it, the original balance stays the same. Here's what I have: models.py class Card(models.Model): card_number = models.PositiveIntegerField(primary_key=True) #account_number = models.ForeignKey(Account, to_field='account_number',on_delete=models.CASCADE) pin = models.PositiveIntegerField(default=False) card_name = models.CharField(max_length=30) issue_date = models.DateField() exp_date = models.DateField(default=datetime.now() + timedelta(days=1095)) balance = models.PositiveIntegerField() address = models.CharField(max_length=60) phone_number = models.PositiveIntegerField() #card_status = models.CharField(max_length=30, default='Active') def __str__(self): return self.card_name views.py def deposit(request): if request.method == 'POST': user_pin = request.POST.get('Pin') user_card_number = request.POST.get('Your Card Number') # gets user input for card number amount = request.POST.get('Amount') # gets user input for amount # Cash deposit: Validatation - checks if card number and pin exist and verify user's balance if Card.objects.filter(card_number=user_card_number).exists(): # gets user pin,balance, card name based on user's card number input #pin_number = Card.objects.filter(card_number=user_card_number).pin # error if use this user_balance = Card.objects.get(card_number=user_card_number).balance user_card_name = Card.objects.get(card_number=user_card_number).card_name # performs deposit user_balance += int(amount) # updates database in user's card Card.objects.get(card_number=user_card_number).save() messages.success(request, 'Deposit Success! ' + '$'+ amount + ' has been depositted from card: ' + user_card_name) else: messages.error(request, 'Card Number or Pin is incorrect') return render(request, … -
how to use my base.html template in a view for another app in Django?
I'm trying to implement a newsletter in my footer. My footer is stored in my base.html file, the problem is I need to render this template for a view in another app. Here is my code: @csrf_exempt def new(request): if request.method == 'POST': sub = Subscriber(email=request.POST['email'], conf_num=random_digits()) sub.save() message = Mail( from_email=settings.FROM_EMAIL, to_emails=sub.email, subject='Newsletter Confirmation', html_content='Thank you for signing up for the StockBuckets email newsletter! \ Please complete the process by \ <a href="{}/confirm/?email={}&conf_num={}"> clicking here to \ confirm your registration</a>.'.format(request.build_absolute_uri('/confirm/'), sub.email, sub.conf_num)) sg = SendGridAPIClient(settings.SENDGRID_API_KEY) response = sg.send(message) return render(request, 'index.html', {'email': sub.email, 'action': 'added', 'form': SubscriberForm()}) else: return render(request, 'index.html', {'form': SubscriberForm()}) I want to replace both instance of index.html in the return statements from this view, to base.html. How would I go about doing that? -
Django Rest framework filter many to many through model
I had an issue about filtering retrieving data in relation many to many through model. My corresponding models are: class Product(TimeStamp): brand = models.CharField(max_length= 50) attribute = models.ManyToManyField(Attribute, through='ProductAttribute') model_no = models.CharField(max_length=100) def __str__(self): return self.model_no class Attribute(TimeStamp): name = models.CharField(max_length=200) product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE) def __str__(self): return self.name class AttributeValue(TimeStamp): attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) value = models.CharField(max_length=200) def __str__(self): return self.value My serializers are: class ProductAttributeSerializer(serializers.ModelSerializer): name = serializers.CharField(source='attribute.name', read_only=True) class Meta: model = ProductAttribute fields = ['name', 'value', ] class ProductSerializer(CreatorUpdatorSerializer): attribute = serializers.SerializerMethodField(read_only=True) class Meta: model = Product fields = ['id', 'model_no', 'attribute'] def get_attribute(self, obj): data = obj.productattribute_set serializer_data = ProductAttributeSerializer(data, many=True) return serializer_data.data My viewset is: class ProductViewSet(CreatorUpdatorViewSet): http_method_names = ('get',) serializer_class = ProductSerializer queryset = Product.objects.all() filter_backends = [DjangoFilterBackend, ] filterset_fields = ['attribute__ame', 'attribute__value'] Now I ant to filter products with attribute and their correspponding values like color:red But I'm getting this error: TypeError at /api/product/ 'Meta.fields' must not contain non-model field names: attribute__value What should I do? -
Django Rest Framework: Page Not Found 404 Error while displaying an image
I am trying to use images in my api using django rest framework but I am still getting the error 404 Page not found. Here's my code - Models.py class SampleModel(models.Model): text = models.CharField(max_length=100, null=True, blank=True) image = models.ImageField(upload_to='images/', null=True, blank=True) serializers.py class SampleSerializer(serializers.ModelSerializer): image = serializers.ImageField(max_length=None, use_url=True) class Meta: model = SampleModel fields = ['text', 'image'] views.py class SampleView(generics.ListAPIView, generics.CreateAPIView): queryset = SampleModel.objects.all() serializer_class = SampleSerializer urls.py urlpatterns = [path('sample/', SampleView.as_view(), name='sample')] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, "assets") MEDIA_URL = '/assets/' I tried googling the solution on google and tried few things too but I still get the same error. I tried to create another project and used the same code as above and it is still giving me the same error. -
is it a better idea to learn Django through a 4 years old tutorial
Recently i have finished a python course now want to learn Django, By searching a bit, I got a 'django tutorial' on the you tube channel 'thenewboston' and i just love the way bucky(you tuber) explaining everything, but the problem is this tutorial is approximate 4 years old, so is it a better idea to go throught it and learn programming stuff ? -
Allowing user to Submit form once in Django
i want that user can submit a particular form only once. Is it possible without any js,react.. actually by using django only ?? i have tried something like that -- def apply(request): p=0 if request.method=="POST": p=1 ...do something.. else: ...do something... i have tried to catch the value of p=1, and try to not return the html is it's submitted once , but each time reload makes the value of p=0. i have to save the session ?? or what will be the right way to do this ? can anyone suggest anything please? -
How do I activate python virtual environment from a different repo?
So am working in a group project, we are using python and of the code is on GitHub. My question is how do I activate the virtual environment? Do I make one on my own using the "python virtual -m venv env" or the one that's on the repo, if there is such a thing. Thanks -
Running django app on http/2 or http/2 protocol instead of http/1
Our website is developed using Django 2.1 and it is serving on http/1 protocol, We have set up it on shared Cpanel hosting, So Cpanel gives a graphical interface to handle it. Is there any way, we can switch protocol programmatically or any other ways to do this? Please advice, Thanks -
Django - How to parse result of query from timestamp into format ('%Y-%m-%dT%H:%M:%SZ')
This is my code: now= datetime.now() rts_time = now.strftime('%Y-%m-%dT%H:%M:%SZ') query = FlightSchedule.objects.filter(departure_time__gt = rts_time) I got this result: 'flight_number': 'VJ141', 'departure_time': datetime.datetime(2020, 11, 17, 13, 10), I want it like this 'flight_number': 'VJ141', "departure_time":"2020-11-17 13:10:00+07:00" Currently, using PostgreSQL database: My models: class FlightSchedule(models.Model): .... departure_time = models.DateTimeField(blank=True, null=True) .... class Meta: managed = False db_table = 'flight_schedule' -
Django - my database include " / " so when return it got parsed (changed) into something else
My data base with ID like this: ID : "y8sh7ZQhk\u00a5Ig08R7pzA8bpei2gUa8n69132NmTXb\u00a5lk=" When I do query: Database.objects.filter It returns something like this ID: 'y8sh7ZQhk¥Ig08R7pzA8bpei2gUa8n69132NmTXb¥lk=' My models: ID = models.CharField(primary_key=True, max_length=200) -
Append html code with variables using jquery / javascript
I am having trouble generating html code from jqavascript/jquery in a html template rendered in django. I have to append html code and also insert some values in between. Right now I am doing a crude string append like this var features =['a','b'] for (var i=0;i<features.length;i++){ var html_code = "<div class = 'feature' <h2>"+features[i]+"</div> $("#features").append(html_code) } For html code <div id="features"></div> What is the right and cleanest way to do this. I know templating is the way to go but there seem to be so many different ways - inline javascript, external library like mustache,handlebar, using django's own template solution - it's very confusing