Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix [ERROR] [2699022] wsgiHandler pApp->start_response() return NULL?
I'm setting up a new server "LiteSpeed" , I am using Django 2.1.7 web framework every thing was good until i uploaded from admin a photo with a name contains Arabic letters this image gives me an error "The server encountered an unexpected condition which prevented it from fulfilling the request." so i review the server log and found that link throws an error 2019-06-09 00:26:17.429165 [ERROR] [2699022] wsgiHandler pApp->start_response() return NULL. Traceback (most recent call last): File "/home/qassimchalets/virtualenv/Py/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 139, in __call__ set_script_prefix(get_script_name(environ)) File "/home/qassimchalets/virtualenv/Py/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 179, in get_script_name script_url = get_bytes_from_wsgi(environ, 'SCRIPT_URL', '') or get_bytes_from_wsgi(environ, 'REDIRECT_URL', '') File "/home/qassimchalets/virtualenv/Py/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 204, in get_bytes_from_wsgi return value.encode('iso-8859-1') UnicodeEncodeError: 'latin-1' codec can't encode characters in position 23-26: ordinal not in range(256) i have searched a lot with no good result so i changed this line return value.encode('iso-8859-1') with return value.encode('utf-8') in the core of the framework it works now for the link of the photo and other photos I don't know if it will affect another things , as I changed in django handler core without any idea what this is really doing class WSGIRequest(HttpRequest): def __init__(self, environ): script_name = get_script_name(environ) # If PATH_INFO is empty (e.g. accessing the SCRIPT_NAME URL … -
Why do my Django messages get duplicated?
I'm using django messages system to show a toast message. I tried to prevent users from accessing "logout" when they are not logged in, and show a warning toast. When I type in the url the first time, it didn't show up anything, but since the second time, it keeps showing 2 toast messages. I tried using this solution but instead of removing my duplicate message, it doesn't show up anything more. def logout_request(request): if not request.user.is_authenticated: messages.warning(request, "You must log in to log out!") return redirect("/") logout(request) messages.info(request, "Logged out successfully!") return redirect("/") <div class="message-wrapper"> {% for msg in messages %} <div class="toast" data-autohide="true" data-delay="1500"> {% if msg.tags == 'success'%} <div class="toast-header toast-header-success"> <strong class="mr-auto">Success</strong> {% elif msg.tags == 'info'%} <div class="toast-header toast-header-primary"> <strong class="mr-auto">Information</strong> {% elif msg.tags == 'warning'%} <div class="toast-header toast-header-warning"> <strong class="mr-auto">Warning</strong> {% elif msg.tags == 'error'%} <div class="toast-header toast-header-danger"> <strong class="mr-auto">Error</strong> {% endif %} <button type="button" class="ml-2 mb-1 close button-close" data-dismiss="toast" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="toast-body"> {{ msg }} </div> </div> {% endfor %} </div> -
Is there a way to modify the Django form and set the selection range of the select box I want?
I have a question about django django form Is there a way to modify the Django form and set the selection range of the select box I want? What I want is: When I type in MyShortCut model Restricts the selection of the category field to only author == request.user Here are the model and view code. class Category(models.Model): name = models.CharField(max_length=25, unique=True) description = models.TextField(blank=True) slug = models.SlugField(unique=True, allow_unicode=True) author = models.ForeignKey(User, on_delete=True) class MyShortCut(models.Model): category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) class MyShortCutForm_input(forms.ModelForm): class Meta: model = MyShortCut fields = ['title', 'content1', 'category'] class MyShortCutCreateView_input(LoginRequiredMixin,CreateView): model = MyShortCut form_class = MyShortCutForm_input # fields = ['title','content1','category'] def form_valid(self, form): ty = Type.objects.get(type_name="input") ms = form.save(commit=False) ms.author = self.request.user ms.type= ty return super().form_valid(form) def get_success_url(self): return reverse('wm:my_shortcut_list') Could it be possible to apply a range condition to the category field by modifying the form? If you know how, I'd like you to tell me how. Thank you -
ValueError: invalid literal for int() with base 10: 'favicon.ico'
I can't figure out why this error is appearing. I understand what the error means, but not why 'favicon.ico' is appearing in the error itself. Rolled back migrations, edited urls.py, wiped the database, rolled back code. Here's the model, if helpful: from django.db import models class DoxpopCase(models.Model): uri_length = 50 minutes_uri = models.CharField(max_length=uri_length) court_payments_uri = models.CharField(max_length=uri_length) charges_uri = models.CharField(max_length=uri_length) case_filed_date = models.DateField() case_number = models.CharField(max_length=25, unique=True) case_local_type_code = models.CharField(max_length=10) case_is_marked_expunged = models.BooleanField() dispositions_uri = models.CharField(max_length=uri_length) as_of_timestamp = models.DateTimeField() case_local_disposition_code = models.CharField(max_length=10, blank=True, null=True) case_local_subtype_code = models.CharField(max_length=10, blank=True, null=True) court_uri = models.CharField(max_length=uri_length) case_uri = models.CharField(max_length=uri_length) case_disposition_date = models.DateField(blank=True, null=True) events_uri = models.CharField(max_length=uri_length) case_global_type_code = models.CharField(max_length=10) case_actors_uri = models.CharField(max_length=uri_length) case_global_disposition_code = models.CharField(max_length=25) case_local_status_code = models.CharField(max_length=15) court_receivables_uri = models.CharField(max_length=uri_length) case_caption = models.CharField(max_length=512, blank=True, null=True) sentences_uri = models.CharField(max_length=uri_length) case_reopen_date = models.DateField(blank=True, null=True) # case_county_fips = models.IntegerField() # archived = models.BooleanField(default=False) def __str__(self): return self.case_number class DoxpopActor(models.Model): class Meta: ordering = ['assigned_case_role', 'actor_person_last_name'] case = models.ForeignKey(DoxpopCase, on_delete=models.CASCADE) actor_full_name = models.CharField(max_length=255) actor_person_first_name = models.CharField(max_length=255, blank=True, null=True) actor_person_last_name = models.CharField(max_length=255, blank=True, null=True) actor_person_middle_name = models.CharField(max_length=50, blank=True, null=True) actor_person_name_prefix = models.CharField(max_length=50, blank=True, null=True) actor_person_name_suffix = models.CharField(max_length=50, blank=True, null=True) actor_uri = models.CharField(max_length=50) assigned_case_role = models.CharField(max_length=100, blank=True, null=True) class DoxpopActorAddress(models.Model): fields = [ 'address_line1', 'address_line2', 'address_line3', 'address_line4', 'address_city', 'address_state_province_code', 'address_postal_code', … -
Addind Datepicker_plus from bootstrap but button inactive
I add bootstrap_datepicker_plus to my code. In my template, I can see the calendar button on the right side of my field but when I click on the button nothing happened try to modify settings, and template organization but nothing changes Hi thanks for that. I still an issue, button on the right side to select date in the template is not working. I click on it but nothing.. this is the code modified: in setting.py # needed for using bootstrap_datepicker_plus BOOTSTRAP3 = { 'include_jquery': True, } and add 'bootstrap_datepicker_plus', in installed apps html file: {% extends 'imports/base.html' %} {% load bootstrap3 %} <!-- necessaire pour date picker --> {% block extra_css %} {{ form.media.css }} {% endblock %} {% block extra_js %} {{ form.media.js }} {% endblock %} <!-- Fin date picker --> {% block title %}Imports Company{% endblock %} {% block heading %}<h3 class="page-header-center">Creation Company</h3> {% endblock %} <hr> <hr> {% block page %} <form method="POST"> {% csrf_token %} <div class="col-lg-4 col-md-4 col-sm-4 content"> {% bootstrap_form company_form %} <button type="submit" class="btn btn-pink pull-right">Create</button> </div> </form> {% endblock %} imports/base.html: {% load staticfiles %} {% load bootstrap3 %} {# import bootstrap4/bootstrap3 #} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> … -
adding UTM paramaters to urls of product in bulk - postgresql django
I'm trying to find a way to add Utm paramaters to every single link column in my postresql using django. The links looks to something like this: https://www.headout.com/tour/5696/united-states/las-vegas/eldorado-canyon-techatticup-mine-tour-premium-group-tour The Utm like the following: ?utm_source=uvergo&utm_medium=ref&utm_campaign=meta And the result would be this: https://www.headout.com/tour/5696/united-states/las-vegas/eldorado-canyon-techatticup-mine-tour-premium-group-tour?utm_source=uvergo&utm_medium=ref&utm_campaign=meta Is there a way to add the parameter in bulk without having to reindex all my datas again? In the views.py or something? Please help. -
Upload Local File Using Django Views/URLs
I am currently working on a project where two users can send each other files. Normally this is not that big of an issue as I would just create a form in html. However, I am hoping to user URLs for a few key functions, mainly retrieving and sending files. Retrieving files is pretty simple, however uploading files using the URL is where I am encountering the problem. Here is what my views.py looks like: def send_message(request, sender_id, receiver_id, file_path): sender_profile = UserProfile.objects.get(id=sender_id) receiver_profile = UserProfile.objects.get(id=receiver_id) message = Message.objects.create(sender=sender_profile, receiver=receiver_profile, audio=file_path) message.save() and here is my urls.py: path('api/send-message/<int:sender_id>/<int:receiver_id>/<str:file_path>', api.send_message), The problem here is that I cant just pass though a files location to be uploaded in the url. I'm a bit of a beginner, but I'm guessing this might be a bit unconventional. The reason I'm doing it this way is because I'm hoping to use the URLs to send and receive data from an Electron/JS desktop application I'm working on. I've looked into the Django REST framework and it's a bit heavy for what I'm hoping to do. Any ideas on how this can be accomplished? Thanks -
Error While dumping sql data into json in django
I am quite new to django. I am trying to convert sql data fetched from a remote postgresql database into JSON so as to use it in react. But while dumping the data it throws as error. `AttributeError: 'str' object has no attribute 'get'` I tried many versions of dumping sql data into json like coneverting data into list and using RealDictCursor but each one of them throws a new error. Views.py from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from django.http import HttpResponse from .marketer import marketer def marketer_list(request): return JsonResponse(marketer) marketer.py (function to fetch data and establish the connection) from django.shortcuts import render, get_object_or_404 import json import psycopg2 from psycopg2.extras import RealDictCursor def marketer(self): connection = psycopg2.connect(user = "db-user", password = "*****", host = "18.23.42.2", port = "5432", database = "db-name") cursor = connection.cursor(cursor_factory = RealDictCursor) postgreSQL_select_Query = "select id from auth_permission" result = cursor.execute(postgreSQL_select_Query) #print("Selecting rows from mobile table using cursor.fetchall") #mobile = dictfetchall(result) #items = [dict(zip([key[0] for key in cursor.description], row)) for row in result] return json.dumps(cursor.fetchall(), indent=2) Error at Url page AttributeError: 'str' object has no attribute 'get' or in some other methods is not JSON serializable -
'OAuth2Token' object has no attribute 'authorize' even with google-auth-httplib2 installed
Trying to build a Google API resource I'm getting an error saying 'OAuth2Token' object has no attribute 'authorize' I read here that a solution is installing google-auth-httplib2 however I have that installed and still running into the error. class Oauth2CallbackView(View): def get(self, request, *args, **kwargs): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES) flow.redirect_uri = 'http://127.0.0.1:8000/profiles/oauth2callback/' credentials = flow.fetch_token(code=self.request.GET.get('code')) b = build(API_SERVICE_NAME, API_VERSION, credentials=credentials) return redirect('http://127.0.0.1:8000/profiles/') PipFreeze: cachetools==3.1.1 certifi==2019.3.9 chardet==3.0.4 Click==7.0 defusedxml==0.6.0 dj-database-url==0.5.0 Django==2.2.1 django-allauth==0.39.1 django-appconf==1.0.3 django-heroku==0.3.1 django-image-cropping==1.2.0 django-multiselectfield==0.1.8 easy-thumbnails==2.6 Flask==1.0.3 google-api-python-client==1.7.9 google-auth==1.6.3 google-auth-httplib2==0.0.3 google-auth-oauthlib==0.3.0 gunicorn==19.9.0 httplib2==0.12.3 idna==2.8 itsdangerous==1.1.0 Jinja2==2.10.1 jsonpickle==1.2 MarkupSafe==1.1.1 oauthlib==3.0.1 Pillow==6.0.0 psycopg2==2.8.2 pyasn1==0.4.5 pyasn1-modules==0.2.5 python-dotenv==0.10.2 python3-openid==3.1.0 pytz==2019.1 requests==2.22.0 -
Python Request local works but not on django local
Trying to request html, using Python-Requests and used to work fine when run on local server localhost:8000 but now I'm hitting captcha preventing me from proceeding. The thing is, it runs fine when running locally from Sublime Text 3 and I get the correct page. Tried session.trust_env = False ALLOWED_HOSTS = ['*'] Always have proxies in request, and tried running server on local IP. proxies = { 'http': 'http://user:pass@xx.xxx.xxx.xx:xxxx' } response = s.get(url, headers=headers, proxies=proxies) soup = BeautifulSoup(response.text, 'lxml') print(soup.prettify()) Getting correct page when script is run from Sublime Text 3. When run on Django local server, always hit with a captcha. -
How to fix "django.contrib.gis.geoip2 has no attribute GeoIP2"
I am trying to retrieve my visitors' location. After successfully retrieving the IP Adress I want to use the GeoIP2 object to get information about the location. https://docs.djangoproject.com/en/2.2/ref/contrib/gis/geoip2/#django.contrib.gis.geoip2.GeoIP2 In my settings.py file I added 'django.contrib.gis.geoip2' to my installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis.geoip2', 'web' ] Using the shell everything works perfect [python3 manage.py shell]: dir(django.contrib.gis.geoip2) ['GeoIP2', 'GeoIP2Exception', 'HAS_GEOIP2', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'base', 'geoip2', 'resources'] However trying to use the GeoIP2 object in my application 'web' I get the error: "django.contrib.gis.geoip2 has no attribute GeoIP2". ['HAS_GEOIP2', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__'] -
Problem In finding information about django framework
I want to learn about python django framework e-commerce. But not finding any tutorial or information how to get start with it. if anyone know kindly helo me with this. -
couldn't find that process type
I am having trouble with the "couldn't find that process type" error on Heroku. I submitted a ticket Thursday but still don't have a solution and they are not open for folks like me on the weekend, so I am posting here. Please note: 1. This is a Django app 2. It runs locally on both heroku local and django runserver, but not heroku itself. 3. I was following a solution I read here: Couldn't find that process type, Heroku which was to take the Procfile out, do a commit, then put it back, and do a commit, and it should work. The output from the push to heroku was the same: remote: Procfile declares types -> (none) So heroku didn't even notice that the Procfile was missing?! Then I put the Procfile back, And I still get the same error: 2019-06-08T18:49:34.853568+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=lj-stage.herokuapp.com request_id=d592d4e6-7558-4003-ab55-b3081502f5cf fwd="50.203.248.222" dyno= connect= service= status=503 bytes= protocol=http I've also read about multiple buildpacks needing to be in a certain order, which might cause this error, but I only have one: (hattie-nHCNXwaX) malikarumi@Tetuoan2:~/Projects/hattie/hattie$ heroku buildpacks › Warning: heroku update available from 7.7.8 to 7.24.4 === lj-stage Buildpack URL … -
what does this line mean:content = "%s new errors%s:\n```\n%s\n```" % (count, extra, "\n".join(lines))
i was trying to understand a Django code when this line popped up: content = "%s new errors%s:\n\n%s\n" % (count, extra, "\n".join(lines)) can anyone help me figure out the meaning of this line? def send_log_dev(file_name, count, lines, extra=""): content = "%s new errors%s:\n\n%s\n" % (count, extra, "\n".join(lines)) dev_client.send_message({ "type": "stream", "to": "logs", "subject": "%s on %s" % (file_name, platform.node()), "content": content, }) -
Swiper.js not working correctly with multiple Bootstrap4 modals in Django template
i have the following problem: I am creating a blog with an optional image gallery for each post. The gallery opens in a modal after you click on the preview picture and then up to 4 pictures are displayed as a swiper-gallery. The problem is, that only the first modal that is opened displays the gallery with all the js applied to it. When I open the next one, I can drag the pictures, but the slider does not work correctly. However when I resize the browser window it starts to work correctly. The same goes for every following gallery that is opened. I experimented a lot putting the script inside and outside of the loop with or without different HTML classes. At this point I am guessing it has something to do with 'shown.bs.modal' within the jQuery .on() method only loading once. But I don't know how to fix that. HTML: {% for post in posts %} <!--preview picture--> <img src="{{ post.image_0.url }}" class="blog-pic" data-toggle="modal" data-target="#{{ post.slug }}"> <!--modal--> <div class="modal fade" id="{{ post.slug }}"> <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">{{ post.title }}</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <div class="swiper-container {{ post.slug }}"> … -
What is the correct way to use class attributes in Django models?
I have the following models: class Foo(models.Model): ... def some_function(self, some_condition): if some_condition: # Do something class Bar(models.Model): ... foo = models.ForeignKey(Foo) _some_condition = False def save(self, *args, **kwargs): # Do something that sets the `_some_condition` class # attribute based on some conditions self.foo.some_function(self._some_condition) super(Bar, self).save(*args, **kwargs) In short, my Bar class has a class attribute called _some_condition. This is set in the save function, and then used to call the Foo class's some_function() method. Now my question is this, is a class attribute the correct way of doing things? Or should I over-ride the __init__() method and set the _some_condition as an instance attribute. What even is the difference between the two? I'm generally confused about class and instance attributes in Python. Moreover, should a post-init signal be used instead of over-riding the method? Thanks for any help. -
How do I differentiate between admin login and the user login from the same login template?
How do I differentiate between admin login and the user login in Django.I want to create single login template?If the login is from the user I want to redirect into different template than the admin. -
counting visits in class based view. declaring it in model
is there easier way to count the number of visits to the post in class based view? class Post(models.Model): views = models.IntegerField(default=0) views.py class PostListByMostViewedView(ListView): model = Post template_name = 'community/mostviewed_home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-views'] paginate_by = 5 -
ModuleNotFoundError: No module named 'polls'
I am following the official Django tutorial on https://docs.djangoproject.com/en/2.2/intro/tutorial01/ but somehow I am not able to run the server as I have created the polls app and added the required urls. When I use the command "py mysite\manage.py runserver" it returns me ModuleNotFoundError: No module named 'polls' error. Project Folder available at https://i.stack.imgur.com/bbxfW.png #views.py from django.http import HttpResponse def index(request): return HttpResponse('<h1><this is a test page</h1>') #urls.py in polls from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] #urls.py in mysite\mysite from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] #settings.py INSTALLED_APPS = [ 'polls', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] [1]: https://i.stack.imgur.com/bbxfW.png -
Django ManyToManyField connected to field inside another model. (Project Management)
I have a SchoolClass with Members. I now want to make a Project that connects to some of the members. How do I do that? class SchoolKlass(models.Model): name = models.CharField(max_length=50) members = models.ManyToManyField(UserProfile, blank=True,related_name='a') class Meta: verbose_name_plural = 'Klasser' def __str__(self): return self.user.username class Project(models.Model): members = models.ManyToManyField(SchoolKlass.members, blank=True) name = models.CharField(max_length=200) description = models.CharField(max_length=1000) schoolKlass = models.ForeignKey(SchoolKlass, on_delete=models.CASCADE) As you can see, I want to access SchoolKlass.members inside the manytomany relationship of the Project model. -
Pass a django datetime to a golang server with json
Here is my django model : class Data(models.Model): created = models.DateTimeField(null=True, blank=True, editable=False) modified = models.DateTimeField(null=True, blank=True) raw = models.TextField(null=True, blank=True) uuid = models.CharField(blank=True, null=True, max_length=48,unique=True) used = models.BooleanField(default=False,null=True) name = models.CharField(blank=True, null=True, max_length=200) geohash = models.CharField(blank=True, null=True, max_length=200) def __str__(self): return str(self.created) + ":" + str(self.raw) def __unicode__(self): return str(self.created) + ":" + str(self.raw) def save(self, *args, **kwargs): """ On save, update timestamps """ if not self.uuid : self.uuid = str(uuid.uuid4().hex) +str(random.randint(1000,9999) ) if not self.id: self.created = timezone.now() self.modified = timezone.now() # if not self.geoHash and (self.gpsLat and self.gpsLong): # Geohash.encode(self.gpsLat, self.gpsLong) return super(DataLbc, self).save(*args, **kwargs) def toJson(self): ret = {} ret["Created"] = str(self.created) ret["Modified"] = str(self.modified) ret["Used"] = self.used ret["Raw"] = self.raw return ret Here is the way that i send it to my golang server : from RawOffer.models import Data while True: try : for data in Data.objects.all()[:10]: requests.post("http://127.0.0.1:8087/convert/",json=data.toJson()) except Exception as e: print(e) time.sleep(5) Now my golang server : package main import ( "database/sql" "encoding/json" "fmt" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/jmoiron/sqlx" "github.com/lib/pq" "strings" "gopkg.in/guregu/null.v3" ) type RawOffer struct { RawOfferData string json:"Raw" Modified null.Time json:"Modified" Created null.Time json:"Modified" } func convertLbc(c *gin.Context) { var rawOffer RawOffer c.BindJSON(&rawOffer) fmt.Println(rawOffer.Created) var err error s := strings.Split(rawOffer.RawOfferData, "ads":) s2 := … -
Bootstrap popover not working despite being initialized (script tags issue?)
I'm trying to add bootstrap popovers to buttons on my webapp but for some reason they don't show. I'm initiating popovers in .js script in my Django template with: $('[data-toggle="popover"]').popover(); I've tried variety of similar implementations, yet without any success. Despite using code that works in fiddles I cannot recreate the effect within my app. I'm assuming it's a matter of script tags, yet trying same tags as in some solutions didn't help much either. Is there some conflict or am I short of some tags? Here are my script tags: <!-- Bootstrap CSS --> <link href="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"> <link href="../static/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen"> <!-- Fonts--> <link href="https://fonts.googleapis.com/css?family=Open+Sans|Prosto+One&display=swap" rel="stylesheet"> <!-- Theme style --> <link rel="stylesheet" href="../static/bootstrap/css/style.css"> <!--star ratings--> <link rel="stylesheet" href="{% static 'star-ratings/css/star-ratings.css' %}"> <script type="text/javascript" src="{% static 'star-ratings/js/dist/star-ratings.min.js' %}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> -
Django's DB API can't come back with all results
I'm trying to list all Characters from a User, but my code only return the first Character, can someone lend me a hand? I'm using the User class from django.contrib.auth.models package. models.py class Character(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name views.py def sheetList(request): charL = get_list_or_404(Character, pk=request.user.id) return render(request, 'sm/sheetList.html',{'charList': charL}) -
How to make google chart using ajax and json in django?
I want to insert google chart using json file. this is the one views.py function to load json file. => def get_addresses(request): addresses = Address.objects.all().values('address', 'postalcode', 'country', 'latitude', 'longitude') addresses_list = list(addresses) return JsonResponse(addresses_list, safe=False) and this is one of the example of json => [{"address": "\uc11c\uc6b8 \uac15\ub0a8\uad6c \uac1c\ud3ec2\ub3d9 ", "postalcode": "135993", "country": "Republic of Korea", "latitude": "37.4896011", "longitude": "127.0687685"} I don't know why it doesn't show up google chart. I got the address from google map api randomly generated. I think google chart could read the address which looks like a key or something. So I don't think it's the problem of address. Can anyone please tell what is the problem? <html> <head> <script type="text/javascript" src='https://www.gstatic.com/charts/loader.js'></script> <script type='text/javascript' src='https://www.google.com/jsapi'> </script> <script type="text/javascript"> google.charts.load('current', { 'packages': ['geochart'], // Note: you will need to get a mapsApiKey for your project. // See: 'mapsApiKey': 'AIzaSyBZ20X5YvOthFtpf48PMJbCek6456cfSTM' }); google.charts.setOnLoadCallback(drawMarkersMap); function drawMarkersMap() { var jsonData = $.ajax({ url: "senders_list.json", dataType: "json", async: false }).responseText; var data = google.visualization.arrayToDataTable(jsonData); var options = { region: 'KR', displayMode: 'markers', colorAxis: {colors: ['green', 'blue']} }; var chart = new google.visualization.GeoChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> </head> <body> <div id="chart_div" style="width: 900px; height: 500px;"></div> </body> </html> -
Unable to set many to many relationship in overwritten save method
I am trying to create a system where I set up an issue and it automatically creates custom fields that a user will have defined stored in another model. I set my current model up with a many to many relationship to the custom field model and overwrite the save method so that each of the custom defined fields will be added with a default value. When I use the .add method after saving my issues model, nothing seems to happen, the many to many relationships are not created. The relationships are able to be made within the Django Admin interface. class Issue(models.Model): class Meta: verbose_name = "Issues" verbose_name_plural = "Issues" title = models.TextField(null=False, blank=False) description = models.TextField() owner = models.ForeignKey(Organisation, on_delete=models.CASCADE) category = models.ForeignKey(IssueCategory, on_delete=models.CASCADE) state = models.ForeignKey(IssueStates, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) assignedTo = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) customFields = models.ManyToManyField(IssueCustomFields, blank=True) def save(self, *args, **kwargs): super(Issue, self).save(*args, **kwargs) for x in IssueCustomFieldDefinitions.objects.filter(owner=self.owner): issueCustom = IssueCustomFields.objects.create( value=x.default, fieldDefinition = x, owner = self.owner, ) self.customFields.add(issueCustom) print(self.customFields.all()) I expect that when the Issue model is saved, it iterates through all the custom fields that th user has set up and creates an instance of it as well as establishing relationships. …