Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django save field
im currently trying to save a field (pubpgp) with a none vaule if the user does not provide any information on that (it's optional). But for some reason i'm not able to save the actuall form without providing the information for the field "pubpgp"... how to solve this? def edit_profile(request): if request.method == 'POST': form = UserForm(request.POST, instance=request.user) try: pubpgp = PGPKey.from_blob(request.POST['pubpgp'].rstrip("\r\n"))[0] except: messages.add_message(request, messages.INFO,"PGP-Key is wrong formated.") return render(request, 'edit_profile.html', {'form': form}) if pubpgp.key_algorithm == PubKeyAlgorithm.RSAEncryptOrSign: form.save() messages.add_message(request, messages.INFO, "Profile has been updated successfully.") return redirect(reverse('home')) else: messages.add_message(request, messages.INFO, "PGP-Key is wrong formated.") return render(request, 'edit_profile.html', {'form': form}) else: form = UserForm(instance=request.user) args = {'form': form} return render(request, 'edit_profile.html', args) models.py pubpgp = models.TextField(blank=True, null=True, max_length=3000, unique=True) -
How to display object of two forms in template
I want to display username using {{ object.first_name }}. I am not able to display it. I am also using User in-built module where UserProfile is linked with OneToOneField. profile.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="col-md-6 grid-margin stretch-card"> <div class="card"> <div class="card-body"> <h4 class="card-title">Profile Information - {{ object.first_name }}</h4> <form class="forms-sample" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ u_form|crispy }} {{ p_form|crispy }} <button class="btn btn-success mr-2" type="submit">Update</button> </form> </div> </div> </div> <ul> {% for key, val in object %} <li>{{ key }}: {{ val }}</li> {% endfor %} </ul> {% endblock content %} Views.py def userProfileUpdate(request, pk): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=User.objects.get(id=pk)) p_form = UserProfileForm(request.POST, request.FILES, instance=UserProfile.objects.get(user_id=pk)) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'Profile Updated!!!') return redirect('users') else: u_form = UserUpdateForm(instance=User.objects.get(id=pk)) p_form = UserProfileForm(instance=UserProfile.objects.get(user_id=pk)) context ={ 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) UserProfile Model class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) -
Multiple forms generated by for loop in django templates: how to handle them?
[The aim in a nutshell] I am trying to create a view to change the payment status of some lines of a table (Consultations). Each of the unpayed consultations appears as a row on the page generated by a for loop in the template (a pretty convenient solution). Ideally, each line should contain a field to change the value from 0 to whatever_decimal_value and there should be only one button to press once the changes are made. [the problem] I am not sure how to build my view (post) so that every change only affects the relevant consultation. I thought of filtering by form id (where I putted {{c.id}}). I am pretty sure there is a simpler and more elegant solution but, since I am new to web dev, I could not find it. Any thoughts? (be direct, I need to learn) Here is the view: class ComptaDetail(Compta): template = loader.get_template("psy/comptadetail.html") initial = {'payed':0} form_class = AdjustPayed def get(self,request, month): user = request.user adjust_form = self.form_class(initial=self.initial) unpayed = Consultations.objects.filter(owner_id=user.id, payed=0, date__month = month) context = {'unpayed' : unpayed, 'adjust_form' : adjust_form} return HttpResponse(self.template.render(context, request)) def post(self,request, month): adjust_form = self.form_class(request.POST) print(adjust_form) Here is the template: <table class="u-full-width"> <tr> <th>Date</th> <th>Prénom</th> … -
Django list of choices in MultipleChoiceField
I would like to display in a form every existing graph_id that exists in the GraphData model. like so: GRAPHS_CHOICES = (GraphData.objects.all().values_list("graph_id", flat=True).distinct()) class GraphForm(forms.Form): graphs = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=GRAPHS_CHOICES) class GraphData(models.Model): graph_id = models.CharField(max_length=128) date = models.DateField(max_length=128) The problem is that choices expects a tuple, and not a list of id's. How can I supply it with a list anyway? -
How to unit test that django.messages shows a message when duplication creations
Here are the creation view class StorageCreateView(CreateView): model = Storage form_class = StorageForm def post(self, request, **kwargs): request.POST = request.POST.copy() name = request.POST['name'] # branch_id = request.POST['branch'] check_name = Storage.objects.filter(name=name) if check_name.count() != 0: messages.error(request, 'يوجد مخزن بهذا الاسم من قبل') return redirect('erp_system_storage_create') else: pass return super(StorageCreateView, self).post(request, **kwargs) now all that I need is to test this part of showing a message if I try to create a new object with the same name Here is my Test.py part : class StorageTest(TestCase): def create(self, name="only a test"): x = Branch.objects.create(name='testing_for_storage') return Storage.objects.create(name=name, branch=x) def test_creation(self): w = self.create() self.assertTrue(isinstance(w, Storage)) self.assertEqual(w.__str__(), w.name) def test_duplicate_creation(self, name="only a test"): self.create() response = self.client.post(reverse('erp_system_storage_create'), {'name': name}) messages = list(get_messages(response.wsgi_request)) current = messages[0] self.assertEqual(current.message, 'يوجد مخزن بهذا الاسم من قبل') it gives me an error from the line current = messages[0] that says IndexError: list index out of range -
Django: Suggestion for models design
I need help with creating models for my simple Django app. The purpose of the application is to let users (referees) register for matches, then admin will choose 2 users (referees) from the list of registered for given match. Right now my Matches model looks like below: class Match(models.Model): match_number = models.CharField( max_length=10 ) home_team = models.ForeignKey( Team, on_delete=models.SET_NULL, null=True, related_name='home_team' ) away_team = models.ForeignKey( Team, on_delete=models.SET_NULL, null=True, related_name='away_team' ) match_category = models.ForeignKey( MatchCategory, on_delete=models.SET_NULL, null=True ) date_time = models.DateTimeField( default=timezone.now ) notes = models.TextField( max_length=1000, blank=True ) What I thought to do is to create new Model named MatchRegister where I will be saving match_id and user_id, something like below: class MatchRegister(models.Model): match_id = models.ForeignKey( Match ) user_id = models.ForeignKey( Users ) And than admin will have list of registered user for given match from witch he will choose two, so I thought to modify my Match model like this (add two new Fields): class Match(models.Model): match_number = models.CharField( max_length=10 ) home_team = models.ForeignKey( Team, on_delete=models.SET_NULL, null=True, related_name='home_team' ) away_team = models.ForeignKey( Team, on_delete=models.SET_NULL, null=True, related_name='away_team' ) match_category = models.ForeignKey( MatchCategory, on_delete=models.SET_NULL, null=True ) date_time = models.DateTimeField( default=timezone.now ) notes = models.TextField( max_length=1000, blank=True ) ref_a = models.ForeignKey( Users, … -
"How to fix error in running the web server?"
So I am currently in a virtual environment, and when I type the command line: python manage.py runserver I encounter this problem: Unhandled exception in thread started by .wrapper at 0x000002B3E84C7598> Traceback (most recent call last): File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django\core\management\commands\runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django\core\management__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\Beatrice\Desktop\django2\myvenv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\Beatrice\AppData\Local\Programs\Python\Python37\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'reset_migrations' My current Django version 2.0.9. -
the current database router prevents this relation
I am not able to do a reverse relationship lookup for foreign key field. I get below error. model b had foreign key on model a with related_name given. Multiple database is configured. But the foreign key relation is on the same database. I tried to mention database using "using" method. It is not working. My django version is 1.11.15. Any idea why this is happing.? It will be very helpful if any provide pointers. ~/venv/with_line_profiler/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py in set(self, instance, value) 224 elif value._state.db is not None and instance._state.db is not None: 225 if not router.allow_relation(value, instance): --> 226 raise ValueError('Cannot assign "%r": the current database router prevents this relation.' % value) 227 228 # If we're setting the value of a OneToOneField to None, we need to clear ValueError: Cannot assign "": the current database router prevents this relation. -
Django ORM: Min('field',filter=...) causes TypeError: can only concatenate list (not "tuple") to list
There is a model Location which can have many Ticket objects (using ForeignKey). The Ticket model has price field which is a DecimalField. Now I have FILTERED QuerySet of Ticket objects and I want to get QuerySet of Location objects and annotate min_price value which is a min price for all Ticket objects from the FILTERED QuerySet. For example: tickets = Ticket.objects.filter(something) locations = Location.objects.all().annotate(min_price=) What I tried: locations_annotated = Location.objects.all().annotate( min_price=Min('tickets__min_price', filter=tickets)) This doesn't work. When I try to get a first element from locations_annotated, debugger returns: TypeError: can only concatenate list (not "tuple") to list Do you know what to do? -
'function' object has no attribute 'objects'
I am trying to get a query set which contains post based on usernames which are stored in model "FollowingProfiles". so models and corresponding views is as follows:- from django.contrib.auth.models import User class Profile(models.Model): Follwers=models.IntegerField(default='0') user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) bio=models.TextField(max_length=120,blank=True) location=models.CharField(max_length=30,blank=True) birth_date=models.DateField(null=True,blank=True) verified=models.BooleanField(default=False) ProfilePic=models.ImageField(upload_to='UserAvatar',blank=True,null=True) def __str__(self): return self.user.username @receiver(post_save,sender=User) def update_user_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class FollowingProfiles(models.Model): Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) ProfileName=models.CharField(max_length=120,blank=True,null=True) def __str__(self): return self.ProfileName class post(models.Model): Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) Picture=models.ImageField(upload_to='PostMedia',blank=True,null=True) DatePosted=models.DateTimeField(default=timezone.now) Content=models.TextField(blank=True,null=True) def __str__(self): return self.Profile.user.username views.py def feed(request): if request.user.is_authenticated: userprofile=FollowingProfiles.objects.filter(Profile__user=request.user) for p in userprofile: postuser=post.objects.filter(Profile__user__username=p.ProfileName) usrpost+=postuser return render(request,'feed/feed.html',{'usrpost':usrpost}) else: return redirect('signup') It produces following error:- function' object has no attribute 'objects' C:\Users\G COMTECH SYSTEM\django-projects\saporaapp\sapora\views.py in feed, line 45 line 45 is postuser=post.objects.filter(Profile__user__username=p.ProfileName) -
Jinja - Arithmetic Operations Using Model Variables
I'm using Django, and I want to convert a variable in my view from m/s to km/h. Currently, my code looks like this: <tr> <td colspan="2">Wind Speed</td> <td>({{weather.wind_speed}} / 1000) * 3600 m/s</td> </tr> What is the correct syntax to do it? -
Django Framework forms
My problem is that user is registered in database but it is not logged in. only those users are able to logged in which are created from admin panel of django This is model view -
How to test a function which returns something and has side effect?
I have a function which returns something but has a side effect at the same time. Should I test only value which this function returns or I need to test result of a side effect too? @slack_interactions.on('admin_add') def handle_admin_add(payload): team_id = payload['team']['id'] user_id = payload['user']['id'] action_value = payload['actions'][0]['selected_options'][0]['value'] user = SlackUser.objects.find_by_ids(team_id, action_value) if user and not user.is_bot: user.make_admin() return build_admins_message(team_id, user_id) -
Django templating. get titel of category
i'm currently trying to figure out how i can display the categories title in my template. Im trying to implement a filter view and this is the last step needed. currently i get the following output Latest Post's in <QuerySet [<Category: testcategory>]> template.html <h1 class="center">Latest Post's in {{ categories }}</h1> < right here!!! {% for post in posts %} <div class="post"> <h3><u><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></u></h3> <p>{{ post.content|safe|slice:":1000"|linebreaksbr}} {% if post.content|length > 500 %} <a href="{% url 'post_detail' pk=post.pk %}">... more</a> {% endif %}</p> <div class="date"> <a>Published by: <a href="{% url 'profile' pk=post.author.pk %}">{{ post.author }}</a></a><br> <a>Published at: {{ post.published_date }}</a><br> <a>Category: <a href="{% url 'category_by' pk=post.category.pk %}">{{ post.category }}</a></a><br> <a>Tag(s): {{ post.tag }}</a><br> <a>Comment(s): {{ post.comment_set.count }}</a> </div> </div> {% endfor %} views.py def category_show(request, pk): list_posts = Post.objects.get_queryset().filter(category_id=pk).order_by('-pk') paginator = Paginator(list_posts, 10) # Show 10 Posts per page page = request.GET.get('page') posts = paginator.get_page(page) categories = Category.objects.all() return render(request, 'myproject/post_list_by_category.html', {'posts': posts, 'categories': categories}) -
Display Dropdown Search Django
i am display list of users. Now i want a search dropdown list which will display the companies and according to those companies list of users will be displayed. Please provide me a way to do search and list users and the same time. i am sharing a image with you people. Thanks in advance. class UserListView(LoginRequiredMixin, generic.TemplateView): template_name = 'users/users.html' def get_context_data(self, **kwargs): context = super(UserListView, self).get_context_data(**kwargs) context['users'] = User.objects.exclude(userprofile__user_role__role_title='Super Admin') # Pass Form to display inside search box return context -
Is it bad practice to store a timer object in a database and also have the program continuously query in Django?
I am a beginner in Django and Python in general and have been practicing by making a browser-based multiplayer game. In the game, registered players can "attack" other players. Once a player has "attacked" a player he must wait 30 minutes before his ability to 'attack' again is reset. I have an idea of implementing this but am not sure if my approach is bad practice: I thought about adding a "TimeToReset" field in the database to each registered user and fill that field with a timer object. Once a player 'attacks' his 'TimeToReset' field starts counting down from 30 minutes to 0. and then have the application continuously query all the users in the database with a while True loop, looking for users that their "TimeToReset" reached 0. And then run code to reset their ability to 'attack' again. I am not sure how efficient my approach or if it is even possible is and would love some input. So to summarize: 1)Is it ok to store a timer/stopwatch object(which continuously changes) in a database? 2)Is it efficient to continuously run a while true loop to query the database? Or if is there a better approach to implement this … -
unable to run django project under apache server
I have created one virtual environment in /var/www/python3 using pipenv and then created django project and installed all dependencies my Pipfile is: [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] django = "==2.1.4" django-rest-swagger = "*" mysqlclient = "*" django-cors-headers = "*" pillow = "*" djangorestframework = "*" django-extra-fields = "*" djangorestframework-xml = "*" django-filter = "*" [requires] python_version = "3.6" my wsgi.py file is: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "image_management.settings") application = get_wsgi_application() my urls.py is: from django.contrib import admin from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from image_app import views as image_view from django.urls import path, include from rest_framework import routers from django.conf.urls.static import static from django.conf import settings from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='Pastebin API') router = routers.DefaultRouter() router.register(r'images', image_view.ImageViewSet) router.register(r'albums', image_view.AlbumViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(router.urls)), url(r'^swagger/$', schema_view) ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) I have ran my apache using : sudo service apache2 restart when i try to access the admin page in django using http://10.75.12.254/admin/ I am getting the followinf error Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at webmaster@localhost to inform them … -
Pytest Django with override_settings ignored
The override of Django settings in my Pytest test method does not seem to work. My test method is as follows: @pytest.mark.django_db def test_ip_range(rf, custom_fixture): with override_settings(IP_RANGE = [IPNetwork('1.0.0.0/8')]): request = rf.get('/') request.user = UserFactory() response = custom_fixture.process_request(request) assert isinstance(response, HttpResponseForbidden) However, while debugging the process_request method I noticed that IP_RANGE in settings is just the default, nothing is overridden. I also tried the settings fixture as a parameter, with the same results. What am I missing? -
Django POST request always empty but it is not
I'm a noob with Django. I try to display the content of a POST request but I don't succeed. I'm using POSTMAN to produce POST request. This is my view in Django : @csrf_exempt def prem(request): if request.method == 'GET': print("GET") context = {'contenu': request.GET.get("name") } # do_something() elif request.method == 'POST': for i in request.POST: print(i) datar = request.POST.get('mykey','rien') context = { 'contenu' : datar } return render(request, 'polls/seco.html', context) When I click on POST in POSTMAN, this is what my shell display : So, my web app receive the POST request, but I cannot get its content. This my template : {% if contenu %} {% csrf_token %} <p>{{ contenu }}</p> <p>Contenu detecté.</p> {% endif %} This is what POSTMAN display : If someone could help me it would be really great ! :) -
How to access post from username only?
I am writing models and i want to access post from username directly in django views. Is it possible? the models.py file is as follows:- from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.utils import timezone #this is how profile of a sample user, say MAX looks like class Profile(models.Model): Follwers=models.IntegerField(default='0') user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) bio=models.TextField(max_length=120,blank=True) location=models.CharField(max_length=30,blank=True) birth_date=models.DateField(null=True,blank=True) verified=models.BooleanField(default=False) ProfilePic=models.ImageField(upload_to='UserAvatar',blank=True,null=True) def __str__(self): return self.user.username @receiver(post_save,sender=User) def update_user_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class post(models.Model): Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) Picture=models.ImageField(upload_to='PostMedia',blank=True,null=True) DatePosted=models.DateTimeField(default=timezone.now) Content=models.TextField(blank=True,null=True) def __str__(self): return self.Profile.user.username -
Django on Debian 9 - ImportError: No module named 'PROJECT.settings.py'
I'm trying to deploy my Django app on Google compute engine Debian VM instance, I have installed the Python(3.6) and setup virtual environment then clone my Django application which is working perfectly well on the local system. When I try to run python manage.py migrate command it returns an error as: ImportError: No module named 'Fetchors.settings.py'; 'Fetchors.settings' is not a package Here's my Fetchors/wsgi.py: import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(path) if path not in sys.path: sys.path.append(path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Fetchors.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) What can be wrong here? Thanks in advance! -
How to chain annotation in Django ORM?
I have a table like this a | b | c | sample_type | value 1 2 3 xx 0 1 34 45 yy 1 1 2 3 xx 1 Now I want to find the unique row count(unique based on the values combined by column a, b, c), sum('values) group by sample_type in Django ORM. So far I have tried this values('sample_type', 'a', 'b', 'c'). \ annotate(positive_temp=Sum('values'), total_temp=Count('a')). \ values(name=F('sample_type'), pos=F('values'), tot=F('total_temp')). \ annotate(positive=Sum('pos'), total=Sum('tot')) but on the last annotate it throws error can not do sum on aggregated values -
Handle ajax request with Django LoginRequiredMixin after session timeout
This situation was covered in other posts, but in most cases solutions are outdated and apply only to function-based views. My problem is simple: Right now my app enforces session timeouts on Django site with this parameters: SESSION_SAVE_EVERY_REQUEST = True SESSION_COOKIE_AGE = 600 And most of views utilize LoginrequiredMixin. It works fine, but with the AJAX it obviously won't work. The common solution found over internet is changing the behaviour of authentication controll to return 403. Is it possible to super the LoginRequiredMixin to do so for ajax requests? Or maybe just giveup and do this fully with javascript, on client side? -
I want to fetch the html content loaded from url in iframe and want to display it in another iframe in Django?
<div class="box"> <iframe src="https://api.cloudconvert.com/convert/" enctype="multipart/form-data" frameborder="2" name="frame1" scrolling="yes" width="600" height="712" align="right" > </iframe> <form method="POST" action="https://api.cloudconvert.com/convert/" enctype="multipart/form-data" target="frame1"> <input type="file" name="file"> <input type="hidden" name="apikey" value="EwzmwYg9LNggAcJdCfg0i5kPQqVSZPMnsYZw1KczeWJTuBlsT0uceQmKBllQppoA"> <input type="hidden" name="inputformat" value="pdf"> <input type="hidden" name="outputformat" value="html"> <input type="hidden" name="input" value="upload"> <input type="hidden" name="timeout" value="10"> <input type="hidden" name="wait" value="true"> <input type="hidden" name="download" value="inline"> <input type="hidden" name="save" value="true"> <input type="submit" value="Convert!"> </form> </div> The above is my html code to load the content of my iframe. def pdf_html(request): tag = [] try: html = open("/home/sevenbits/pro/project/myproject/templates/pdf_html/iframe.html") except HTTPError as e: print(e) except URLError: print("Server down or incorrect domain") else: res = BeautifulSoup(html.read(), "html5lib") tag = res.find('iframe') src = tag['src','enctype'] #URl of iframe ready for scraping return render(request,'pdf_html/iframe.html') This is my view to display the content of the html page. I want to simply take code of html page loaded in the iframe and display it to my another iframe and I'm using the beautifulsoup library. -
Django google maps error 'This page can't load Google Maps correctly.'
Im using django_google_maps app in my django project . I added GOOGLE_MAPS_API_KEY in my settings.py. here is my user model: class UserData(AbstractBaseUser): first_name = models.TextField(null=False) last_name = models.TextField(null=False) email = models.EmailField(null=False, unique=True) id_code = models.CharField(null=False, max_length=11) profile_picture = models.ImageField(null=True, blank=True) rank = models.IntegerField(default=0) # here is google map fields address = map_fields.AddressField(max_length=200, null=True) geolocation = map_fields.GeoLocationField(max_length=100) And already added this code in my ModelAdmin class formfield_overrides = { map_fields.AddressField: { 'widget': map_widgets.GoogleMapsAddressWidget(attrs={'data-map-type': 'roadmap'})}, } But when i want to add user in admin panel this error occurs in map section From google : This page can't load Google Maps correctly. Do you own this website? Anyone can help ?