Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use django signals with model creation?
This is my UserClass models and i want to use django signals to set user in UserClass model to the user registred in the site. from django.contrib.auth.models import User class UserClass(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) I came up with this code but it doesn't work. def user_create(sender, instance, created, **kwargs): if created: UserClass.objects.create( user=instance, ) print('User created') post_save.connect(user_create, sender=User) -
Django choice select after render related foreignkey fields[txt or file field]
I am working on test series module. I stuck adding question with option. I have a question model and related with option models(objective base question and descriptive base question) and want to add option according question type. I am looking for your valuable suggestion. class Questions(models.Model): ques_type = ( ('SCQ', 'Single choice questions'), ('MCQ', 'Multiple choice questions'), ('OQ', 'Descriptive'), ) title = models.TextField(_("Question Title")) difficulty_level = models.ForeignKey("DifficultyManager.Difficulty", verbose_name=_( "Difficulty Level"), on_delete=models.SET_NULL, null=True) topics = models.ForeignKey("TopicManager.Topic", verbose_name=_( "Topic"), on_delete=models.SET_NULL, null=True) ques_type = models.CharField( _("Question Type"), max_length=4, choices=ques_type) is_delete = models.BooleanField(_("Delete"), default=False) created_by = models.ForeignKey(User, related_name="questions", blank=True, null=True, on_delete=models.SET_NULL) status = models.BooleanField(_("Status")) create_date = models.DateTimeField( _("Created timestamp"), auto_now_add=True) update_date = models.DateTimeField( _("Last update timestamp"), auto_now=True) objects = QuestionsManager() def __str__(self): return self.title class QuestionOption(models.Model): question = models.ForeignKey( "Questions", on_delete=models.CASCADE, verbose_name=_("questions")) option = models.CharField(_("Choice"), max_length=255) is_right = models.BooleanField(_("Right/Worng"), default=False) create_date = models.DateTimeField( _("Created timestamp"), auto_now_add=True) update_date = models.DateTimeField( _("Last update timestamp"), auto_now=True) class Meta: unique_together = [ ("question", "option"), ] def __str__(self): return self.question.title class QuestionFile(models.Model): question = models.ForeignKey( "Questions", on_delete=models.CASCADE, verbose_name=_("questions"), null=True) image = models.ImageField(_("Image"), upload_to='question/images/%Y/%m/%d', height_field=None, width_field=None, max_length=400, null=True) video = models.FileField( _("Video"), upload_to='question/videos/%Y/%m/%d', max_length=100, null=True) create_date = models.DateTimeField( _("Created timestamp"), auto_now_add=True) update_date = models.DateTimeField( _("Last update timestamp"), auto_now=True) def __str__(self): … -
Autofill state while user enter zip code by using zip code database|Django|JQuery|UI
How to auto fill state by entering zip code. I have zip code database. How to validate with in form. If user enters the zip code that zip code is available in this database using that zip code the state should autofill as mention below datbase.If zip code matches then state must autofill I have implemented this using API. But know I have to do with database INSERT INTO pages_zip_code (id, zip, city, st) VALUES (1, '00501', 'Holtsville', 'NY'), (2, '00544', 'Holtsville', 'NY'), (3, '00601', 'Adjuntas', 'PR'), (4, '00602', 'Aguada', 'PR'), (5, '00603', 'Aguadilla', 'PR'), (6, '00604', 'Aguadilla', 'PR'), (7, '00605', 'Aguadilla', 'PR'), (8, '00606', 'Maricao', 'PR'), (9, '00610', 'Anasco', 'PR'), (10, '00611', 'Angeles', 'PR'), (11, '00612', 'Arecibo', 'PR'), (12, '00613', 'Arecibo', 'PR'), (13, '00614', 'Arecibo', 'PR'), (14, '00616', 'Bajadero', 'PR'), (15, '00617', 'Barceloneta', 'PR'), (16, '00622', 'Boqueron', 'PR'); urls.py path('autostate', views.autostate, name='autostate'), views.py def autostate(request): if 'term' in request.GET: qs = zip_code.objects.filter(zip__iexact=request.GET.get('term')) zip_li = list() for zip_n in qs: zip_li.append(zip_n.st) return render(request, 'home.html') html page:- <input class="InputZip" name="Zip" placeholder="Zip Code" type="text"> <input class="Inputstate" name="state" placeholder="State" type="text"> *JQuery* <script> function is_int(value) { if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) { return true; } else { return false; } } $(".InputZip").keyup(function() { … -
Avoid running script when refreshing page in Django
I am running my external python script using submit button on my web page script.py: def function(): print('test it') views.py from script import function def func_view(request): if request .method == 'POST': function() return render('my.html',{'run_script':function}) Problem: when I am opening my page, program is running, it's not waiting until I will click this button. additionally: when I add in my if request loop File input, after refreshing web page , Django is adding same file again. What I am doing wrong here? -
I have deleted django's debug.log file in a Django app which is running in a ubuntu server using Apache. It has stopped working after that
When I go to the url it shows 500 Internal server error. Apache is running. I get the following when I open Apache's log file: [Thu Oct 01 00:05:58.928187 2020] [mpm_event:notice] [pid 3300:tid 139714918706112] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured --$ [Thu Oct 01 00:05:58.942594 2020] [core:notice] [pid 3300:tid 139714918706112] AH00094: Command line: '/usr/sbin/apache2' [Thu Oct 01 01:48:01.623516 2020] [mpm_event:notice] [pid 3300:tid 139714918706112] AH00491: caught SIGTERM, shutting down [Thu Oct 01 01:48:01.801650 2020] [mpm_event:notice] [pid 8340:tid 140123896040384] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured --$ [Thu Oct 01 01:48:01.801791 2020] [core:notice] [pid 8340:tid 140123896040384] AH00094: Command line: '/usr/sbin/apache2' [Thu Oct 01 02:39:31.890115 2020] [mpm_event:notice] [pid 8340:tid 140123896040384] AH00491: caught SIGTERM, shutting down [Thu Oct 01 02:39:32.025560 2020] [mpm_event:notice] [pid 9367:tid 139790829341632] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured --$ [Thu Oct 01 02:39:32.025705 2020] [core:notice] [pid 9367:tid 139790829341632] AH00094: Command line: '/usr/sbin/apache2' [Thu Oct 01 08:33:15.700373 2020] [mpm_event:notice] [pid 9367:tid 139790829341632] AH00491: caught SIGTERM, shutting down [Thu Oct 01 08:33:15.789098 2020] [mpm_event:notice] [pid 13931:tid 139952318925760] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -$ [Thu Oct 01 08:33:15.789241 2020] [core:notice] [pid 13931:tid 139952318925760] AH00094: Command line: '/usr/sbin/apache2' I have created a new debug.log file but it is empty now. I think it might be … -
Django - How to apply onlivechange on CharField / IntegerField
I want to hide the field form.name_of_parent_if_minor if the age (CharField) < 18 else show. I am not getting where to write jQuery or JS code or add separate js file. For this do I need to the html definition and add tag for age (CharField) or we can perform action on this as well. I am new to the Django so if you find any mistakes in my code then any help would be appreciated for guidance. forms.py class StudentDetailsForm(forms.ModelForm): class Meta: model = StudentDetails views.py class StudentCreateView(LoginRequiredMixin, CreateView): template_name = 'student/student_details_form.html' model = StudentDetails form_class = StudentDetailsForm success_url = "/" html {% extends 'student/base.html' %} {% load crispy_forms_tags %} {% block content %} <div id="idParentAccordian" class="content-section"> <form method="POST"> {% csrf_token %} <div class="card mt-3"> <div class="card-header"> <a class="collapsed card-link" style="display: block;" data-toggle="collapse" href="#idPersonalInformation">Personal Information</a> </div> <div id="idPersonalInformation" class="collapse show" data-parent="#idParentAccordian"> <div class="card-body"> <div class="row"> <div class="col-6"> {{ form.joining_date|as_crispy_field }} </div> <div class="col-6"> {{ form.class|as_crispy_field }} </div> </div> {{ form.student_name|as_crispy_field }} {{ form.father_name|as_crispy_field }} {{ form.mother_name|as_crispy_field }} {{ form.gender|as_crispy_field }} <div class="row"> <div class="col-6"> {{ form.date_of_birth|as_crispy_field }} </div> <div class="col-6"> {{ form.age|as_crispy_field }} </div> </div> <div> {{ form.name_of_parent_if_minor|as_crispy_field }} </div> </div> </div> </div> <div class="form-group mt-3"> <button class="btn btn-outline-info" … -
how I can to migrate this python script to django? [closed]
I tried to migrate this python script to Django but without success: import asyncio import websockets async def hello(websocket, path): name = await websocket.recv() print(f"< {name}") greeting = f"Hello {name}!" await websocket.send(greeting) print(f"> {greeting}") start_server = websockets.serve(hello, "localhost", 8055) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() -
Form not looking good without using crispy form
This is the form that appears if I donot use crsipy form.But, if I use crispy forms, the radio button disappears, anyone have any idea?? As shown above, if crispy form is used, the radio button now disapperas.what is the issue?? <form method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success" formaction="{% url 'addcustomer' %}">Submit</button> <button class="btn btn-primary" formaction="{% url 'customerlist' %}">Cancel</button> </form> -
Django: preventing concurrency in related models without using a lock
Let's say I have 4 models, as such: class Venue(models.Model): capacity = models.IntegerField() class Event(models.Model): description = models.CharField() class Session(models.Model): event = models.ForeignKey(Event) start = models.TimeField() end = models.TimeField() class UserSession(models.Model): venue = models.ForeignKey() user = models.ForeignKey(User) event = models.ForeignKey(event) session = models.ForeignKey(Session) class Meta: unique_together = ['user', 'venue', 'event'] So a user has to choose 1 session out of an event, and can only attend one session. A user is limited to a single venue (this integrity is enforced elsewhere). The number of user sessions is limited by the venue capacity. Events and sessions can happen in multiple venues. The question is, how best to prevent concurrency resulting in the number of UserSessions exceeding the venues capacity. Given that events and sessions are not unique to events and venues and occurring elsewhere the use of pessimistic lock wouldn't make sense. One thing I've considered is relating Sessions to Venues via a M2M relationship using a through model, and tracking an indicator field, such as attendance. This would work in both the pessimistic and optimistic approach, as a lock could be placed on the through model, or attendance could be used to confirm no changes in the optimistic approach. I … -
Django - how to update manytomany field using UpdateView and ModelForm
I have following models(not actual names). class MyModelTwo(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) class MyThroughModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) foo = models.ForeignKey(MyModelTwo, null=True, on_delete=models.CASCADE) bar = models.ForeignKey('MyModelOne', null=True, on_delete=models.CASCADE) original_price = models.DecimalField(_('original price'), max_digits=8, decimal_places=2) off = models.DecimalField(_('off'), max_digits=8, decimal_places=2) final_price = models.DecimalField(_('final price'), max_digits=8, decimal_places=2) class MyModelOne(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) foos = models.ManyToManyField(MyModelTwo, through='MyThroughModel') In my CreateView I have following. db_obj = form.save(commit=False) db_obj.save() for item in form.cleaned_data['items']: throughModel= MyThroughModel() throughModel.original_price = item.original_price throughModel.foo = item throughModel.bar = db_obj throughModel.off = item.off throughModel.final_price = item.final_price throughModel.save() return super(MyCreateView, self).form_valid(form) This saves things correct. Now the problem is how do I make sure that UpdateView inserts new entries(items) and also removes the items which have been unselected by the user? What is the way to handle that in the form_valid inside UpdateView? I looked into some questions related to M2M but couldn't find something fitting my case. Maybe I got tired of searching and trying. I spend hours on this but no luck. I am new to this. Please help. Thank you. -
How to group by? Django Rest Framework
I am developing an API Rest based on Django, I have two models: Album Track I am trying to get the right format on this JSON (this is what I am getting now): [ { "album": "album-123kj23mmmasd", "track": { "id": 6, "uuid": "2c553219-9833-43e4-9fd1-44f536", "name": "song name 1", }, "duration": 2 }, { "album": "album-123kj23mmmasd", "track": { "id": 7, "uuid": "9e5ef1da-9833-43e4-9fd1-415547a", "name": "song name 5", }, "duration": 4 }, This is what I would like to reach, I would like to group by 'albums': [ { "album": "album-123kj23mmmasd", "tracks": [{ "id": 6, "uuid": "2c553219-9833-43e4-9fd1-44f536", "name": "song name 1", "duration": 2 }, { "id": 7, "uuid": "9e5ef1da-9833-43e4-9fd1-415547a", "name": "song name 5", "duration": 4 }, ] }, ] Thanks in advance -
Django Template - Nested Dictionary Iteration
My template receives from views.py following nested dictionary of shopping cart content. {'20': {'userid': 1, 'product_id': 20, 'name': 'Venus de Milos', 'quantity': 1, 'price': '1500.00', 'image': '/media/static/photos/pngegg.png'}, '23': {'userid': 1, 'product_id': 23, 'name': 'Bicycle', 'quantity': 1, 'price': '1000.00', 'image': '/media/static/photos/366f.png'}} I am having problem with iteration through it. For example, when I am using following code, {% for key, value in list %} {{ key }} {{ value }} {% endfor %} instead of keys and values I receive just this: 2 0 2 3 My goal is to calculate grand total through multiplying quantity and price for each product and dding it all together with each product in cart. May sombody give me a hand on this, or at least help to figure out how to iterate properly through nested dictionary? -
AttributeError at / 'QuerySet' object has no attribute 'users'
I don't know why I am getting this error I am new to Django I researched a lot but I didn't find an answer please when giving me the answer explain as much as you can I want to learn but if you don't want to no problem Thank you, This is my Views.py from django.views.generic import TemplateView from django.shortcuts import render, redirect from django.contrib.auth.models import User from home.forms import HomeForm from home.models import Post, Friend class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): form = HomeForm() posts = Post.objects.all().order_by('-created') users = User.objects.exclude(id=request.user.id) friend = Friend.objects.filter(current_user=request.user) friends = friend.users.all() args = { 'form': form, 'posts': posts, 'users': users, 'friends': friends } return render(request, self.template_name, args) def post(self, request): form = HomeForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() text = form.cleaned_data['post'] form = HomeForm() return redirect('home:home') args = {'form': form, 'text': text} return render(request, self.template_name, args) def change_friends(request, operation, pk): friend = User.objects.get(pk=pk) if operation == 'add': Friend.make_friend(request.user, friend) elif operation == 'remove': Friend.lose_friend(request.user, friend) return redirect('home:home') This is my models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): post = models.CharField(max_length=500) user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Friend(models.Model): users = … -
use nested list in django template
I have a 1d queryset and I want it to be nested based on its each value. For example, in a template like below <ul> {% for dept in dept_queryset %} <li>{{ dept.code }} {{ dept.name }}</li> {% endfor %} </ul> I see something like this 1000 a 1100 b 1200 c 2000 q 2100 w 2110 e 2111 t ... 2200 t 2210 h 2211 b ... 2300 p What I want is however something like this: 1000 a 1100 b 1200 c 2000 q 2100 w 2110 e 2111 t ... 2200 t 2210 h 2211 b ... 2300 p I can hard code each queryset and use it in as context, but I'd like to know if there is any pythonic way. I tried divisible by filter, with no success. And I'm aware that I should change my template tag of course, I hope to get some guidance about it. Any help would be appreciated. Thanks! -
Cannot access Django query string parameter in url
I am trying to access the 'category' key from the following url within my view: ...users/8/feed?category='x'. However, when I run self.kwargs within my view, it only returns 'user_id': 8. urls.py: path('users/<int:user_id>/feed', views.Posts.as_view()) views.py: class Posts(APIView): def get(self, request, **kwargs): return Response(self.kwargs) What would I change such that self.kwargs returns "user_id": 8, "category": 'x' rather than just "user_id": 8? It is important that this stays as a query string parameter using '?'. Additionally, I've seen other people implementing similar things using self.request.GET, what is the difference between using this and self.kwargs? Thanks, Grae -
Django select related of select related
I have a Student model which has a foreign key to a School model (related name is school) which has itself a FK to a Country model (related name is country). I want to select the Student along with its school and country. Do I need to write this: student = Student.objects.filter(pk=123).select_related("school", "school__country").first() student.school # use object cache student.school.country # use object cache or is this enough: student = Student.objects.filter(pk=123).select_related("school__country").first() -
Django unable to upload image file
I was trying out InageField in the models, But Image upload do not work when I try to upload from the forms. But it works when I upload it from the admin page. Any way to debug is also helpful My model- class Inventory(models.Model): """docstring for Inventory""" name = models.CharField(max_length=100,default='Something') image = models.ImageField(null=True, blank=True) description = models.CharField(max_length=100, default='Describe Something') price = models.IntegerField( default=0) My Form- class InventoryForm(forms.ModelForm): class Meta: model = Inventory fields = ['name','description','price','image'] widgets = { 'name' : forms.TextInput(attrs={"placeholder":"Name", "onfocus":"this.value = '';","onblur":"if (this.value=='') this.value = this.defaultValue","required":""}), 'description' : forms.TextInput(attrs={"placeholder":"Email", "onfocus":"this.value = '';","onblur":"if (this.value=='') this.value = this.defaultValue","required":""}), 'price' : forms.NumberInput(attrs={"placeholder":"Price","onfocus":"this.value = '';","onblur":"if (this.value=='') this.value = this.defaultValue","required":""}), } Settings - MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media/") template - <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <input type="submit" value="Send"> </form> url - from django.contrib import admin from django.urls import path, include, re_path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',include('inventory.urls')), path('<int:id>',include('inventory.urls')), path('admin/', admin.site.urls), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Regards, Deepak Dash -
Geodjango: transform() swaps lat/long incorrectly
I'm using geodjango and load a shapefile as follows: datasource = DataSource("/path/to/shape.shp") for each in datasource[0]: geo = each.geom geo.transform(4326) What I'm trying to do here is to transform a geometry to 4326 so I can record it in my database, which uses this SRID. However, a rather odd thing happens. When I run this locally (using GDAL 2.4.0, Django 3.0.6) this works perfectly fine. Here is an example of a polygon that is transformed. Input: POLYGON ((141192.63413501 167690.231242441,141198.39365501 167695.515882441... Which is then transformed into: POLYGON ((4.24376514198078 50.8195815928706,4.24384675060931 50.819629186136... This works well. However, when this runs in production (GDAL 3.0.4, Django 3.0.3), then this fails in a very weird way. There is no error message, and the transform() function does its thing... but it reverses latitude and longitude! So my output becomes: POLYGON ((50.8195818670687 4.24376485512428,50.8196294603646 4.24384646375124... I can not fathom why this happens...?! It all seems to be fine, expect for this very odd swapping of lat/long. -
Search a generated format in Django Database
In my django app I am creating Barcodes with a combination of str and id of model and id of product. The barcode is generated but the problem that I am encountering is when I scan the barcode I want to show the information of the product scanned. I'll be able to understand the problem with code in a better way Models.py class GrnItems(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE) item_quantity = models.IntegerField(default=0) item_price = models.IntegerField(default=0) label_name = models.CharField(max_length=25, blank=True, null=True) class Grn(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) reference_no = models.CharField(max_length=500, default=0) items = models.ManyToManyField(GrnItems) Views.py def PrintGRNsv1(request, pk): grn = Grn.objects.filter(pk=pk)[0] grn_prod = grn.items.all() print("grn prod", grn_prod) items = [] for i in grn_prod: for j in range(i.item_quantity): items.append({'bar': "YNT9299" + str(pk) + str(i.item.pk) + str(j + 1)} ) Now let's suppose I generated a Barcode YNT92991231, Now I have no idea how to get the i.item.pk from this code How can I do this ? -
heroku invalid phone number
when deploying an app with add-ons it tells me The account "****@." is not permitted to install the sendgrid add-on at this time. Your account may require additional verification. Please visit https://tools.heroku.support/addons-verification to complete this process. It asks me for my phone number , but when entering it , i see " This number is not supported. Please contact support. " -
What happens If an SQL query takes more time and the left age of CONN_MAX_AGE is less?
Using: Django 1.10 and MySQL I would like to timeout a query when a particular query takes longer time. One closest thing I found is this. https://docs.djangoproject.com/en/1.10/ref/settings/#conn-max-age CONN_MAX_AGE The lifetime of a database connection, in seconds. Use 0 to close database connections at the end of each request — Django’s historical behavior — and None for unlimited persistent connections. Let's assume the following scenario: CONN_MAX_AGE is set to 5 seconds On an average, each DB query takes 3 seconds. Request #1 comes in and since there is no active conn, It creates a connection and set the connection age to 5 seconds. Request #1 finishes after 3 seconds and age left for conn to expire is 2 seconds. Now, Request #2 comes in, Since the conn is available it uses the old open conn. Now, What happens to Request #2? Will it finish successfully or Will it terminate because the conn this query is using has less time left to expire? -
How to made updates to a site deployed on digital ocean [closed]
I have django website hosted on digital ocean. I want to make some changes to the static html page and database. Can i use filezilla to do this? What would be the easiest method to do this updates. Please guide me -
1049, "Unknown database 'tester_gk1chOZhTJ4l'" when trying to access db view from a user in django
I am using multiple dbs and changing databases based on specific users/vendor permissions in Django. I am able to create dbs and models dynamically. 1046, 'No database selected' - unable to create programmatically the models (created with models.Model definition) The db model was created but when accessing the data in the view I get the same error. Seems like the database is not changed dynamically. Here is the code I am using class RouterMiddleware(MiddlewareMixin): def process_view(self, request, view_func, args, kwargs): requser = request.user try: userobj = User.objects.get(username=requser) except: userobj = None if userobj: try: usr = CompanyUser.objects.filter(user=userobj)[0] except: usr = None if usr: request_cfg.cfg = { "id": usr.company.db_name, "ENGINE": usr.company.engine, "NAME": usr.company.db_name, "USER": usr.company.user, "PASSWORD": usr.company.password, "HOST": usr.company.host, "PORT": usr.company.port, "ATOMIC_REQUESTS": False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None, usr.company.db_name: { 'CHARSET': None, 'COLLATION': None, 'NAME': None, 'MIRROR': None } } else: request_cfg.cfg = {"id": 'default'} if not request_cfg.cfg.get("id") in settings.DATABASES: from django.db import connections connections.databases[request_cfg.cfg.get( "id")] = request_cfg.cfg settings.DATABASES.update({ request_cfg.cfg.get("id"): request_cfg.cfg }) The middlewares and db routers are registered. class DatabaseRouter (object): def _default_db(self, model): apps = ["auth", "sessions", "contenttypes", "admin", "setupsaas"] if hasattr(request_cfg, 'cfg'): if request_cfg.cfg.get('id') != None: if model._meta.app_label in apps: return 'default' return request_cfg.cfg.get('id') else: … -
TypeError at / 'ModelBase' object is not iterable .....How to resolve thsi in django
TypeError at / 'ModelBase' object is not iterable .....How to resolve this in django? Here is my models.py:- from django.db import models class City(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Meta: verbose_name_plural = 'cities' views.py:- import requests from django.shortcuts import render from . models import City Create your views here. def home(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=37dcd1bbdc2216925ebb043a870105a6' cities = City.objects.all() weather_data = [] for city in City: city_weather = requests.get(url.format(city)).json() weather = { 'city' : city, 'temperature' : city_weather['main']['temp'], 'description' : city_weather['weather'][0]['description'], 'icon' : city_weather['weather'][0]['icon'] } weather_data.append(weather) context = {'weather_data' : weather_data} return render(request,'home.html',context) Please solve this as i am a beginner in Django -
In JavaScript code combining two functions not working, but in single function works fine
CS50 WEB's project3 mail When I use single funciton it works properly which is function compose_email() { // Show compose view and hide other views document.querySelector('#read-view').style.display = 'none'; document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; // Clear out composition fields document.querySelector('#compose-recipients').value = ''; document.querySelector('#compose-subject').value = ''; document.querySelector('#compose-body').value = ''; document.querySelector('#compose-form').onsubmit = function() { let recipient = document.querySelector('#compose-recipients'); let subject = document.querySelector('#compose-subject'); let body = document.querySelector('#compose-body'); fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: recipient.value, subject: subject.value, body: body.value, }) }) .then(response => response.json()) .then(result => { console.log(result); }); load_mailbox('sent') return false; }; }; But when I split it into two function it doesn't load load_mailbox('sent') function compose_email() { // Show compose view and hide other views document.querySelector('#read-view').style.display = 'none'; document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; // Clear out composition fields document.querySelector('#compose-recipients').value = ''; document.querySelector('#compose-subject').value = ''; document.querySelector('#compose-body').value = ''; document.querySelector('#compose-form').onsubmit = function() { send_email(); }; }; function send_email() { let recipient = document.querySelector('#compose-recipients'); let subject = document.querySelector('#compose-subject'); let body = document.querySelector('#compose-body'); fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: recipient.value, subject: subject.value, body: body.value, }) }) .then(response => response.json()) .then(result => { console.log(result); }); load_mailbox('sent') return false; };