Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I wanna send localhost:8000/accounts/detail ,but it cannot be done
I wanna send localhost:8000/accounts/detail ,but it cannot be done. I wrote in views.py def login(request): login_form = LoginForm(request.POST) regist_form = RegisterForm(request.POST) if regist_form.is_valid(): user = regist_form.save(commit=False) context = { 'user': request.user, 'login_form': login_form, 'regist_form': regist_form, } return HttpResponseRedirect('detail') if login_form.is_valid(): user = login_form.save(commit=False) login(request, user) context = { 'user': request.user, 'login_form': login_form, 'regist_form': regist_form, } return HttpResponseRedirect('detail') context = { 'login_form': login_form, 'regist_form': regist_form, } return render(request, 'registration/accounts/login.html', context) Now in the part of HttpResponseRedirect,it sends localhost:8000/accounts/login/detail so error happens.This page read login method is localhost:8000/accounts/login.I wanna send the url to localhost:8000/accounts/detail.So,how should I fix this? In urls.py,I wrote urlpatterns = [ url(r'^detail$', views.detail,name='detail'), url(r'^login/$', views.login,name='login'), ] -
How can I use django template filter to delete the last character?
I have a string such as 100M, I want to delete the M, how can I do that? I tried use slice filter, but the number length is variable(maybe 1000 or others), so, how can I do that? -
Python Django equals in function arguments. Setting the variable dynamically
I think this is called "Positional arguments" or the opposite or keyword arguments. I have written a script in Python Django and rest framework that has to take in parameters from the user and feed it to the Amazon API. Here is the code; page = request.query_params.get('page'); search = request.query_params.get('search'); search_field = request.query_params.get('search_field'); search_index = request.query_params.get('search_index'); response = amazon.ItemSearch(Keywords=search, SearchIndex=search_index, ResponseGroup="ItemAttributes,Offers,Images,EditorialReview,Reviews") In this code the text Keywords=search varies. That is. It could be like this Actor=search, Title=search, or Publisher=search I am not sure how to make the Keywords part dynamic such that it changes to the user's input such as Actor, Title, or Publisher -
Django post save function not saving
I have post save function that I am trying to execute to update the count on my model. I have tried these two methods of doing the post save, they are all not updating my counter to "5" inside my database after I do a save on my admin page. # method for updating def update_tagpoll(sender, instance, *args, **kwargs): # countptype = c.polltype.count() # TagPoll.objects.count = countptype instance.counter = 5 post_save.connect(update_tagpoll, sender=TagPoll) # method for updating @receiver(post_save, sender=TagPoll, dispatch_uid="update_tagpoll_count") def update_tagpoll(sender, instance, **kwargs): instance.counter == 5 I also tried to do a instance.save()which would lead to a maximum recursion issue(which is expected) below is the model that I am trying to update. class TagPoll(models.Model): title = models.CharField(max_length=120, unique=True) polltype = models.ManyToManyField(Ptype, blank=True) active = models.BooleanField(default=True) counter = models.IntegerField(default=0) def __unicode__(self): return str(self.title) I cant seem to find what the issue, any advice would be appreciated. -
build a follower system which is not between enduser
Usecase The app that I am developing is about linking startup, job seekers and investors. Sorry I could not give the name still though I have developed already around 40% :) .There will be three entities. One is Startup account, Enduser account and Investor account. I am thinking of adding follow/unfollow feature where Enduser can follow Startup and vice-versa Startup can follow Investor and vice-versa Enduser cannot follow other enduser and enduser cannot follow investor For this how should I model my application Here is the model for the entities I talked about Enduser Model class UserSetting(models.Model): user = models.OneToOneField(User) job_interest = models.ManyToManyField(Category, related_name='user') is_email_notification = models.BooleanField( default=True, help_text="Email me job recommendations based on my interests and preferences") class Meta: verbose_name = 'User Setting' verbose_name_plural = 'User Settings' def __str__(self): return self.user.username Startup Model class Startup(models.Model): name = models.CharField(max_length=200, unique=True, blank=False, null=False) slug = models.SlugField(unique=True) description = models.CharField(max_length=400) Investor Model class Investor(models.Model): investor = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False, null=False, help_text='Full Name') slug = models.SlugField(max_length=200, unique=True) contact_email = models.EmailField(null=True, blank=True) # for now I have done like this followers = models.ManyToManyField( User, related_name='followers', blank=True) For now, you can see I have included the followers field in the Investor but … -
AttributeError at /accounts/login/ 'dict' object has no attribute 'status_code'
I got an error,AttributeError at /accounts/login/ 'dict' object has no attribute 'status_code' .My web site's page has login&new account registration in a page. I wrote in views.py def login(request): login_form = LoginForm(request.POST) regist_form = RegisterForm(request.POST) if regist_form.is_valid(): user = regist_form.save(commit=False) context = { 'user': request.user, 'login_form': login_form, 'regist_form': regist_form, } return context if login_form.is_valid(): user = login_form.save(commit=False) login(request, user) context = { 'user': request.user, 'login_form': login_form, 'regist_form': regist_form, } return context context = { 'login_form': login_form, 'regist_form': regist_form, } return render(request, 'registration/accounts/login.html', context) in login.html(I cannot user code format,so I decide to use code snippet) <header class="clearfix"> <h1 class="title">WEB SITE</h1> <ul> <form class="form-inline" method="post" role="form"> {% csrf_token %} <div class="form-group"> <label class="white-letter">LOGIN</label> </div> <div class="form-group"> <label class="sr-only">USERNAME</label> <input id="id_username" name="username" type="text" value="" minlength="5" maxlength="12" placeholder="USERNAME" class="form-control"> </div> <div class="form-group"> <label class="sr-only">PASSWORD</label> <input id="id_password" name="password" type="password" value="" minlength="8" maxlength="12" placeholder="PASSWORD" class="form-control"> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-lg" style="color:white;background-color: #F62459;border-style: none;">LOGIN</button> <input name="next" type="hidden"/> </div> </form> </ul> </header> <main> <div class="heading col-lg-6 col-md-12"> <h2>NEW ACCOUNT</h2> <h3 class="margin-small">ALL FREE</h3> <form class="form-horizontal" method="POST"> <div class="form-group-lg"> <label for="id_username">USERNAME</label> {{ regist_form.username }} </div> <div class="form-group-lg"> <label for="id_email">EMAIL</label> {{ regist_form.email }} </div> <div class="form-group-lg"> <label for="id_password">PASSWORD</label> {{ regist_form.password1 }} </div> <div class="form-group-lg"> <label for="id_password">PASSWORD(CONFORMATION)</label> {{ … -
How can I re-label the "Password" field on the Django 1.11 login page?
I want to customise the appearance of the "Password" field on the Django 1.11 login page. Specifically, I want to change the label from "Password" to "Passphrase" while maximising re-use of default Django code. For other forms I have done this subclassing as follows: from django.utils.translation import ugettext_lazy as _ from x import BaseForm class CustomForm(BaseForm): def __init__(self, *args, **kwargs): super(CustomForm, self).__init__(*args, **kwargs) self.fields["fieldname"].label = _("Custom label") ...but simply subclassing AuthenticationForm has no effect, so I assume I have to hook it up somehow. And/or subclass LoginView? -
Inactive django account with djoser
Hi guys I am trying to log in with an inactive account, I used Djoser, Django Rest Framework but I need to show the correct message to the user. I was testing the API with an inactive account, but I always receive this message: Unable to login with provided credentials. I was studying the code of djoser, and I found that this line of code (https://github.com/sunscrapers/djoser/blob/master/djoser/serializers.py#L95) is never gets execute, because the authenticate method always return None when the user is not active. I can solve the problem with Django ORM, but I think that's is not a fancy solution. I hope can you help me. Thanks in advance. -
'image' is an invalid keyword argument for this function
Here is the error: 'image' is an invalid keyword argument for this function Any help in understanding what is happening and how to fix it would be much appreciated. Basically I have a 'Partner' model with a one to many relationship to a 'Product' model. I am using inlineFormSet for the 'Product' model which has fields like partner, image, desc, price etc. The form displays correctly in admin and when the form is rendered but upon submitting it throws the error. here is my views.py def partner_create(request): #Trying to add multiple product functionality if not request.user.is_staff or not request.user.is_superuser: raise Http404 ProductFormSet = inlineformset_factory(Partner, Product, form=ProductForm, extra=3) if request.method == 'POST': partnerForm = PartnerForm(request.POST or None, request.FILES or None) formset = ProductFormSet(request.POST, request.FILES, queryset=Product.objects.none()) if partnerForm.is_valid() and formset.is_valid(): instance = partnerForm.save(commit=False) instance.save() for form in formset.cleaned_data: image = form['image'] product = Product(partner=instance, image=image) product.save() messages.success(request, "Partner Successfully Created") else: print partnerForm.errors, formset.errors else: partnerForm = PartnerForm() formset = ProductFormSet(queryset=Product.objects.none()) return render(request, "partner_form.html", {"partnerForm": partnerForm, "formset": formset}) here is my models.py class Partner(models.Model): name = models.CharField(max_length=120) logo = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") banner_image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") mission = models.TextField() vision = models.TextField() height_field = models.IntegerField(default=0) width_field = … -
Django Rest Framework creating instance instead of updating
I want to update the Profile instance for a user, by sending data to the url update_profile/ I am using: curl -X PUT -H "Authorization: Token sometoken" -d "name=somename&age=20&user=1" 127.0.0.1:8000/update_profile/ and the error I get is: {"user":["This field must be unique."]} It seems like the error comes because the request creates a new instance of Profile, when there is already another instance of Profile with that same user. But I just want to update the current Profile instance for the user. Any idea why my code does try to create a new instance instead of updating it? views.py class UserProfileChangeAPIView(generics.UpdateAPIView, mixins.UpdateModelMixin): permission_classes = ( permissions.IsAuthenticated, UserIsOwnerOrReadOnly, ) serializer_class = UpdateProfileSerializer parser_classes = (MultiPartParser, FormParser,) def get_queryset(self, *args, **kwargs): queryset = Profile.objects.filter(user=self.request.user) return queryset def get_object(self): self.request.user.profile def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) def update(self, request, pk=None): try: self.request.user.profile except Http404: return Response( {'detail': 'Not found'}, status=status.HTTP_404_NOT_FOUND) return super(UserProfileChangeAPIView, self).update(request, pk) urls.py url(r'^update_profile/$', UserProfileChangeAPIView.as_view(), name='update_profile'), serializers.py class UpdateProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = [ 'name', 'age', 'user', ] models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True) age = models.PositiveIntegerField(null=True) -
Play song audio with django
I have this projet, where users can add songs, and everyone else can play it to listen to the audio (mp3). The problem is, I don't know how to make it play. <td> <button type="button" class="btn btn-success btn-xs"> <span class="glyphicon glyphicon-play"></span>&nbsp; Play </button> </td> -
Django implement search within multiple fields in same data table
This is my models.py file. class CustomerInfo(models.Model): customer_name=models.CharField('Customer Name', max_length=50) customer_mobile_no = models.CharField('Mobile No', null=True, blank=True,max_length=12) customer_price=models.IntegerField('Customer Price') customer_product_warrenty = models.CharField('Product Warrenty',null=True, blank=True,max_length=10) customer_sell_date = models.DateTimeField('date-published', auto_now=True) customer_product_id=models.CharField('Product ID',max_length=150,null=True, blank=True) customer_product_name=models.CharField('Product Name', max_length=50) customer_product_quantity=models.IntegerField('Quantity',default=1) def __str__(self): return self.customer_name Now I want to search in muliple fieds like as customer_name, customer_mobile_no,customer_product_id etc. So I created views.py file def customerPage(request): customers = CustomerInfo.objects.all() if request.method =="GET": customerid = request.GET['customer_id'] try: customers = CustomerInfo.objects.get(pk=customerid) cus_name = CustomerInfo.objects.filter(customer_name__contains=customerid) mobile_number = CustomerInfo.objects.filter(customer_mobile_no__contains=customerid) return render(request, 'shop/customer.html', {"cus_name": cus_name,"mobile_number": mobile_number, "customers": 'customers', "site_name": "Moon Telecom"}) except: return render(request, 'shop/customer.html', {"error": "Not found any info"}) return render(request, 'shop/customer.html', {'customers': customers}) and this is my html file {% extends "shop/base.html" %} {% block content_area %} <div class="col-lg-4"> <div class="customer_search" > <form action="{% url "shop:customerPage" %}" method="GET"> {% csrf_token %} <div class="form-group"> <label for="customer_id">Id:</label> <input type="text" class="form-control" id="customer_id" placeholder="Enter customer ID" name="customer_id"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div> </div> <div class="col-lg-8 customers_info"> {% if error %} <div class="alert alert-danger"> <strong>{{error}}</strong> </div> {% endif %} {% if cus_name %} {% for x in cus_name %} <p>{{x.customer_name}}</p> {% endfor %} {% else %} <p>nothing foung</p> {% endif %} {% if customers %} <table class="table"> <thead> <tr> <th>Name</th> <th>Mobile No</th> <th>Product Name</th> … -
Are there conventions for naming Django project, setting and main app folders?
My Django site currently looks like this: my_store (project folder) docs app_1 admin.py apps.py ... app_2 store (main app folder) my_store (settings folder) settings.py urls.py ... Where: my_store is the name of my project app_1 and app_2 are potentially reusable apps store contains project-specific logic and configuration (likely not reusable) Are there established conventions for giving distinct names to each of: the project folder (my_store) the settings folder (my_store) the main app folder (store) -- I've seen a few examples of calling this "main" De facto / popular conventions welcome, but documented / authoritative conventions preferred. -
Passing multiple parameters to Django URL
I have the LodgingOffer model in which is possible create and lodging offer and detail their data: class LodgingOffer(models.Model): # Foreign Key to my User model created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ad_title = models.CharField(null=False, blank=False, max_length=255, verbose_name='Título de la oferta') slug = models.SlugField(max_length=100, blank=True) country = CountryField(blank_label='(Seleccionar país)', verbose_name='Pais') city = models.CharField(max_length=255, blank = False, verbose_name='Ciudad') def __str__(self): return "%s" % self.ad_title pub_date = models.DateTimeField( auto_now_add=True, ) def get_absolute_url(self): return reverse('host:detail', kwargs = {'slug' : self.slug }) # I assign slug to offer based in ad_title field,checking if slug exist def create_slug(instance, new_slug=None): slug = slugify(instance.ad_title) if new_slug is not None: slug = new_slug qs = LodgingOffer.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" % (slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug # Brefore to save, assign slug to offer created above. def pre_save_article_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_article_receiver, sender=LodgingOffer) To this model, I have one DetailView named HostingOfferDetailView in which I show the data of the LodgingOffer object One important requisite is that in the detail of the LodgingOffer record, I can contact to owner of the offer (user who create the offer) to apply to her. For this purpose, I have the contact_owner_offer() … -
pydoc with django application fails with "AppRegistryNotReady: Apps aren't loaded yet."
i' ve a newly installed virtualenv with python3.4 and Django 1.9.2 . Nothing else is installed. I created a project (pydoctest) and an application (order), added one class to the models, and a line to the INSTALLED_APPS for the application. I ran pydoc -w ./ on the root directory, but it fails on some file. #order/models.py class Alma(models.Model): """Test docstring""" apple = models.CharField(max_length = 12) user@debpra:~/ve/pydoctest$ pydoc -w ./ wrote manage.html wrote order.html wrote order.admin.html wrote order.apps.html wrote order.migrations.html problem in order.models - AppRegistryNotReady: Apps aren't loaded yet. wrote order.tests.html wrote order.views.html wrote pydoctest.html wrote pydoctest.settings.html problem in pydoctest.urls - AppRegistryNotReady: Apps aren't loaded yet. wrote pydoctest.wsgi.html . What do i miss here? What be the right way to use pydoc with Django (1.9.2)? Also if i put import django django.setup() to the pydoctest/init.py, all problem will be solved. What does it exactly do? -
Running django channels with daphne on systemd
First of all, sorry for the long question, I hope a few of you have patience for this. TL; DR: How do I load django settings correctly in systemd? I am following this guide, Deploying Django Channels Using Daphne, so I can run some real-time apps (using WebSockets). Without nginx, and running from the command line the worker (python manage.py runworker) and interface (daphne), I can access the correct channels consumer class, as can be seen in the log below (these were triggered from a javascript client): 2017-10-09 21:10:35,210 - DEBUG - worker - Got message on websocket.connect (reply daphne.response.CYeWgnNQoY!mwuQrazQtv) 2017-10-09 21:10:35,211 - DEBUG - runworker - websocket.connect 2017-10-09 21:10:35,211 - DEBUG - worker - Dispatching message on websocket.connect to api.consumers.OrderConsumer 2017-10-09 21:10:48,132 - DEBUG - worker - Got message on websocket.receive (reply daphne.response.CYeWgnNQoY!mwuQrazQtv) 2017-10-09 21:10:48,132 - DEBUG - runworker - websocket.receive 2017-10-09 21:10:48,132 - DEBUG - worker - Dispatching message on websocket.receive to api.consumers.OrderConsumer These events were triggered by the following javascript calls: ws = new WebSocket("ws://localhost:8000/order/1/") ws.send("test") With nginx, and running both interface and worker on systemd, I get the following log despite using the exact same trigger input. 2017-10-09 20:38:35,503 - DEBUG - worker - Got message … -
is it possible to instantiate django object and then populate values?
I have a django model with a lot of fields so I don't want to create with a constructor. I am trying to save like this: org = Organization() org.name = 'my name' org.save() but it is not saving. How do I save and populate a django object in this way? -
What data type to use for storing version numbers in database in Django
What is the best data type to use for storing version data such as x.x.x ( ex: 1.1.0) using the django model fields. -
Static File Whitenoise Heroku Django issue
I have an API developed in Django and Django Rest Framework. We need one page in "normal" Django that will be open once a month maybe (so no need for CDN for the static files). Gunicorn + whitenoise is what we went ahead with. The collectstatic works fine in both build phase and after build phase. The url generated on the page is href=/static/css/edit_card.a1c6e0f9f12e.css/ Relevant django settings: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_media/') STATICFILES_DIRS = [ os.path.join(BASE_DIR + "/static_folder/"), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' The relevant file in the repo is in /static_folder/css/edit_card.css The relevant file on the heroku instance after running collectstatic is in static_media/css/edit_card.a1c6e0f9f12e.css I can manually access this link url/static/css/edit_card.css which is ridiculously weird. This works fine when DEBUG = True. When in False/production it does not. Could someone point me in the right direction? Thanks. -
I am getting the following error when trying to save this form
Cannot assign "": "Product.partner" must be a "Partner" instance. I am trying to add a one to many relationship between two models. The 'one' model is a 'Partner. The 'many' are 'Product' which contain image description, price, etc. Here are my views.py def partner_create(request): #Trying to add multiple product functionality if not request.user.is_staff or not request.user.is_superuser: raise Http404 ProductFormSet = inlineformset_factory(Partner, Product, form=ProductForm, extra=3) if request.method == 'POST': partnerForm = PartnerForm(request.POST or None, request.FILES or None) formset = ProductFormSet(request.POST, request.FILES, queryset=Product.objects.none()) if partnerForm.is_valid() and formset.is_valid(): instance = partnerForm.save(commit=False) instance.save() for form in formset.cleaned_data: image = form['image'] product = Product(partner=partnerForm, image=image) product.save() messages.success(request, "Partner Successfully Created") else: print partnerForm.errors, formset.errors else: partnerForm = PartnerForm() formset = ProductFormSet(queryset=Product.objects.none()) return render(request, "partner_form.html", {"partnerForm": partnerForm, "formset": formset}) here is my admin.py class ProductImageInline(admin.TabularInline): model = Product extra = 3 #This works originally but doesn't do multiple products class PartnerModelAdmin(admin.ModelAdmin): list_display = ["__unicode__", "timestamp"] inlines = [ProductImageInline,] class Meta: model = Partner admin.site.register(Partner, PartnerModelAdmin) Here is my form.py class PartnerForm(forms.ModelForm): mission = forms.CharField(widget=PagedownWidget(show_preview=False)) vision = forms.CharField(widget=PagedownWidget(show_preview=False)) # publish = forms.DateField(widget=forms.SelectDateWidget) class Meta: model = Partner fields = [ "name", "logo", "banner_image", "mission", "vision", "website_link", "fb_link", "twitter_link", "ig_link", ] class ProductForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: … -
django - How to make a simple shopping cart
I'm at a loss. I've searched most of the links on Google/YouTube and can't seem to figure out how to create a simple session-based cart in Django! My website is NOT an e-commerce store. I have a Post model which users can review via a Comment model. They review the Post's overall quality, overall difficulty, and workload based on a 1-5 rating system. All that I want is for users to be able to go to the Post page, press "Add to Cart" and be redirected to a "cart.html" page where they see the Post they just added, as well as that Post's ratings (Quality, Difficulty, Workload). These ratings come from my Comment model, which is 100% based on User input. I need this cart to exist in the session! It is very important that anonymous users have access to this feature. here's a brief snippet of my models.py class Post(models.Model): [...] title = models.CharField(max_length=250) # rest of code class Comment(models.Model): [...] post = models.ForeignKey(Post, related_name="comments") user = models.ForeignKey(User, related_name="usernamee") [...] overall_rating = models.FloatField(choices=overall_rating_choices, default=None) difficulty_rating = models.FloatField(choices=difficulty_rating_choices, default=None) workload_rating = models.FloatField(choices=workload_rating_choices, default=None) # rest of code I don't need a checkout page, I don't need any payment processing, I … -
How to integrate an Angular app with Django back-end into a Laravel website project
I have developed an API for a quiz which has an Angular Front that uses quite a lot of Statistics in django in the server-side using the pymc package. My main website back-end is meant to be kept PHP. So I have created the initial components with Laravel. I would want to know how to integrate these two in the main website. How do I organize the code? What do i do to make sure that the user can navigate smoothly and also how to optimize the integration workflow? I am literally having no leads on this. Even if someone can suggest some reading material, that would also be fine. I really need to solve this problem. I would be heartily grateful if someone could help me figure out the same. Thanks in Advance. -
Update ends in negative balance after massive update requests Django
Currently, I've this method inside my models.py def charge(self, amount): self.balance = (self.balance - Decimal(amount)) self.save() When A new request comes in I check if that user has current_balance >= price So I can do objectRow.charge(price) the issue is when I get 1000 request to the same ID I end up in -000 negative balance and the users ends up owing me money and that's not the point. This is my validation so far. accountObject = account.objects.get(auth_token=auth_token) if accountObject.balance >= settings.MT_COST: # Save ProductObject = product(application=applicationObject, account=accountObject, cost=settings.MT_COST, direction=2, status_log=1, product=product_id, ip_address=ip_address) ProductObject.save() # Charge User ProductObject.charge(settings.MT_COST) data = {'status': "ok"} return HttpResponse(json.dumps(data), content_type='application/json', status=200) # Not enough Balance else: data = {'status': "error"} return HttpResponse(json.dumps(data), content_type='application/json', status=406) -
Django unicode convertion
I did some research on Unicode strings, but I've unfortunately not been able to figure out why Python does some things. I have this piece of code: output["anything"] = { "type": "Feature", "properties": { "name": "somename", "amenity": "Store", "popupContent": "Store 3 " }, } When I use print(output) it prints this as: {u'anything': u'type': u'Feature', u'properties': {u'amenity': u'Store', u'name': u'somename', u'popupContent': u'Store 3'}} I would however like to have this without the u' ' as my javascript utility won't read this. If the answer would also give me some insight in why this is happening, I would really appreciate that. -
Update seconds dropdown based on the selection of the first dropdown using the database
I have two dropdowns in my HTML. The second select would change depending on the selection of the first one. I want my first element to be the one to make an AJAX call and extract what's inside of my database. I am not quite fluent in jQuery/AJAX and I need help on this one. Here is an example: <select name="menu"> <option value="meat"> Meat </option> <option value="seafood"> Seafood </option> <option value="vegetarian"> Vegetarian </option> <option value="dessert"> Dessert </option> </select> <select name="entrees"> {% for i in meat %} <option value='{{idx.0}}'> {{i.1}} </option> {% endfor %} //more loops for other menu </select> When the user select the type of food, different entrees appears on the second html dropdown. I am using python and django in my backend. The entrees are being updated regularly that is why I can't hardcode the options of the second dropdpwn, as many have suggested on some question here. LET'S SAY: I choose 'meat.' How do I make an ajax call to get all the meat entrees in an array so I can loop into it? I would greatly appreciate it if you can comment lines that are important so I can learn something new. Thank you very much …