Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: 'GeoQuerySet' object is not callable
I am trying to make google map api 3 markers using users' locations in Geodjango, and i encounter Internal Server Error 500 in rendering the google map and markers. On the CMD console , i get TypeError: 'GeoQuerySet' object is not callable. Can you please suggest a solution and explain the cause for the exception? The Views.py class MyView(View): def get(self, request): resp = UserList.objects.all().values('nickname', 'last_location') print (resp) return JsonResponse(request, resp, safe=False) The urls.py from django.conf.urls import include, url from django.contrib import admin from mymap_app import views as map_views admin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^my_endpoint/$',map_views.MyView.as_view(),name='user_list'), url(r'^$',map_views.IndexView.as_view(), name='index'), ] Traceback: Traceback (most recent call last): File "C:\Python35-32\lib\site-packages\django\core\handlers\exception.py", lin e 41, in inner response = get_response(request) File "C:\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187 , in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185 , in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python35-32\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Python35-32\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Kaleab\Desktop\WebMap\AAmap_Project\mymap_app\views.py", line 2 1, in get return JsonResponse(request, resp, safe=False) File "C:\Python35-32\lib\site-packages\django\http\response.py", line 530, in __init__ data = json.dumps(data, cls=encoder, **json_dumps_params) File "C:\Python35-32\lib\json\__init__.py", line 237, in dumps **kw).encode(obj) TypeError: 'GeoQuerySet' object is not callable [05/Sep/2017 22:36:45] "GET /my_endpoint/ HTTP/1.1" 500 18865 -
Queryset Serialize: AttributeError: 'dict' object has no attribute '_meta'
I am trying to pass a queryset as a JSON object: structure=Fund.objects.all().values('structure').annotate(total=Count('structure')).order_by('-total') However, querysets aren't Json Serializable therefore, I modified my code: from django.core import serializers structure=serializers.serialize('json',Fund.objects.all().values('structure').annotate(total=Count('structure')).order_by('-total')) But I get this error: AttributeError: 'dict' object has no attribute '_meta' and this is my queryset: <QuerySet [{'total': 106, 'structure': 'Corp'}, {'total': 43, 'structure': 'Trust'}, {'total': 2, 'structure': 'OM'}, {'total': 0, 'structure': None}]> -
Django/Sencha - HTTPResponse FIle download Not working
response is returning the file contents to the browser. But, filedownload is not happening. Here is the code : Django: file2 = open(os.path.join(filename), 'rb') response = HttpResponse(FileWrapper(file2),content_type='application/force-download' ) response['Content-Disposition'] = 'attachment; filename=test.c' file2.close() Sencha: xtype: 'button', text: 'Generate Code', tooltip: 'Generate Code', disabled: true, itemId: 'generatecode', listeners: { click: { fn: me.getController().onGenCodeClick, scope: me.getController() } } onGenCodeClick: function() { var me = this, view = me.getView(); url = www_paths.backendURL + 'main/test/'; Ext.Ajax.request( { url: www_paths.backendURL + 'main/gencode/', method: 'GET', success: function ( response, opts ) { Ext.core.DomHelper.append( document.body, { tag : 'iframe', frameBorder : 0, width : 0, height : 0, css : 'display:none;visibility:hidden;height:0px;', src : url }); }, }); In browser debugging, Network tab: General: Request Method:GET Status Code:200 OK Remote Address:127.0.0.1:8001 Referrer Policy:no-referrer-when-downgrade Headers: Access-Control-Allow-Origin:* Allow:GET, HEAD, OPTIONS Content-Disposition:attachment; filename="pm_config_target_pbs_ram.c" Content-Encoding:gzip Content-Length:19210 Content-Type:application/force-download Date:Tue, 05 Sep 2017 19:12:29 GMT Server:WSGIServer/0.2 CPython/3.4.0 Vary:Accept, Cookie, Accept-Encoding X-Frame-Options:SAMEORIGIN In response and Preview, i'm seeing the contents of the file to be downloaded. But, not sure why I don't see a file download. -
Django Error - ValueError: Cannot assign "'int": "row name" must be a "ForeignKey" instance
i got this odd error and i don't know why. ValueError: Cannot assign "'36'": "Ofac_Add.number" must be a "Ofac_Sdn" instance. I created the Django Models and they work perfectly. Please find below my models: class Ofac_Sdn(models.Model): number = models.IntegerField(blank=True, null=True) name = models.CharField(max_length=200, null=True) b_i = models.CharField(max_length=250, null=True) programe= models.CharField(max_length=250, null=True) more_info = models.CharField(max_length=250, null=True) vessel_call_sign = models.CharField(max_length=250, null=True) vessel_type= models.CharField(max_length=250, null=True) vessel_dwt = models.IntegerField(blank=True, null=True) tonnage = models.IntegerField(blank=True, null=True) vessel_flag = models.CharField(max_length=250, null=True) vessel_owner= models.CharField(max_length=250, null=True) dob_aka= models.CharField(max_length=250, null=True) #date_of_creation = models.DateTimeField(max_length=250, auto_now=True,blank=True, null=True) #publish_date = models.DateTimeField(max_length=250, auto_now_add=True,blank=True, null=True) #content = models.TextField(blank=True, null=True, default="") class Meta: verbose_name_plural = "ofac_sdn" def __str__(self): return self.number, self.name, self.programe class Ofac_Add(models.Model): number = models.ForeignKey(Ofac_Sdn, on_delete=models.CASCADE) n= models.IntegerField(blank=True, null=True) adresa = models.CharField(max_length=250, null=True) oras_zip = models.CharField(max_length=250, null=True) stat = models.CharField(max_length=250, null=True) ceva = models.CharField(max_length=250, null=True) # date_of_creation = models.DateTimeField(max_length=250, auto_now=True,blank=True, null=True) # publish_date = models.DateTimeField(max_length=250, auto_now_add=True,blank=True, null=True) # content = models.TextField(blank=True, null=True, default="") class Meta: verbose_name_plural = "ofac_add" def __str__(self): return self.number, self.adresa , self.oras_zip class Ofac_Alt(models.Model): number = models.ForeignKey(Ofac_Sdn, on_delete=models.CASCADE) ceva = models.CharField(max_length=500, null=True) aka = models.CharField(max_length=500, null=True) name_of_aka = models.CharField(max_length=500, null=True) a = models.CharField(max_length=250, null=True) # date_of_creation = models.DateTimeField(max_length=250, auto_now=True,blank=True, null=True) # publish_date = models.DateTimeField(max_length=250, auto_now_add=True,blank=True, null=True) # content = models.TextField(blank=True, null=True, … -
Ordenate django query by user
I'm trying to retrieve the objects that some user created and show in my API, but i need to ordenate this objects by this user. If use order_by('created_by') the queryset will be ordenate by user's id (not necessarily the id that i want, but descending order), the firsts results must be the Opportunity that my user created followed by the others. I thought this could resolve, but q lost the ordenation with union: def get_queryset(self): user = self.request.user q_all = Opportunity.objects.all().exclude(created_by=user.id) q_user = Opportunity.objects.filter(created_by=user.id).exclude(archived=True) q = q_user | q_all return q -
Add current date time to the uploaded file in django
I am trying to add date and time to the uploaded file. If the filename is filename.xml then I would like to change the name to filename-<date>-<time>.xml def handle_uploaded_file(self, f): name = "static/uploads/{0}".format(f.name) with open(name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) Any help is highly appreciated. Thanks in advance. -
Django Autocomplete Light List Object has no Attribute Queryset
Please look at my edit at the end of my code as well. I'm attempting to implement django-autocomplete-light (dal) for a single field. Following the tutorial, I turn up this error: 'list' object has no attribute 'queryset'. I have seen this question: django-autocomplete-light error = 'list' object has no attribute 'queryset'. It did not resolve my issue. Why is this error occurring? What can I do to combat this? I have two models: class Entity(models.Model): entity = models.CharField(primary_key=True, max_length=12) entityDescription = models.CharField(max_length=200) def __str__(self): return self.entityDescription class Action(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, db_column='entity') entityDescription = models.CharField(max_length=200) action = models.CharField(max_length=50) def __str__(self): return '%s' % self.entity I have a model form: class ActionForm(ModelForm): class Meta: model = Alert fields = '__all__' widgets = { 'entityDescription': autocomplete.ModelSelect2(url='eda') } I have a view: class EntityDescriptionAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Entity.objects.all() return qs I have a urls.py: urlpatterns = [ url( r'^eda/$', views.EntityDescriptionAutocomplete.as_view(), name='eda', ), ] Thank you for any insight you all might have. Edit: I changed... widgets = { 'entityDescription': autocomplete.ModelSelect2(url='eda'), } ...to... widgets = { 'entityDescription': autocomplete.Select2(url='eda'), } ...this allowed my page to render, but the autocomplete field is an empty dropdown. Why is it empty? -
Deploy Django with mod_wsgi on special port number
I have run Django 1.11.4 with mod_wsgi and Apache2.4 with a virtualenv Python3.4 environment on Centos VPS. After configuring mod_wsgi in virtual hostrunnig and running apachectl restart I get: (98)Address already in use: make_sock: unable to listen for connections on address [::]:80 (98)Address already in use: make_sock: unable to listen for connections on address 0.0.0.0:80 Port 80 is in use for Tomcat: netstat -tulpn | grep :80 tcp 0 0 :::80 :::* LISTEN 29445/httpd tcp 0 0 :::8080 :::* LISTEN 1464/java This is my virtualHost: <VirtualHost *:80> ServerAlias 91.132.233.168 ServerAdmin webmaster@localhost DocumentRoot /opt/rh/httpd24/root/var/www/html Alias /memit /opt/rh/httpd24/root/var/www/html/myproject <Directory /opt/rh/httpd24/root/var/www/> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined WSGIDaemonProcess memit python-path=/opt/rh/httpd24/root/var/www/html/memit:/opt/rh/httpd24/root/va$ WSGIProcessGroup myproject WSGIScriptAlias / /opt/rh/httpd24/root/var/www/html/myproject/myproject/wsgi.py </VirtualHost> My questions: How can I change Django port to special port? -
Installing django also creates migrations
To make a long story short: when I install django it comes with migrations that I deleted in the past. Here is what I do: $ mkvirtualenv foo $ (foo) pip install django Collecting django Using cached Django-1.11.5-py2.py3-none-any.whl Collecting pytz (from django) Using cached pytz-2017.2-py2.py3-none-any.whl Installing collected packages: pytz, django Successfully installed django-1.11.5 pytz-2017.2 Now when I look in the directory where the venv is created I can see migrations in the default django apps (admin, user, ect.) I also see migrations in a brand new project. This problems started after I tried to reset my migrations. I deleted the migrations from each app and dropped all the tables. Then I removed the migrations in the venv, while doing this I accidentally removed a django app. The missing app forced me to uninstall and install django. Even when I tell pip not to use the cache --no-cache-dir, I still get the migrations. -
How to update user data using django and rest framework?
When trying to update a user the following message appears: "A user with this username already exists" I have a standard Django User model and I have another profile template that extends. How do I update this data, including the user profile. Thank you. Model class Profile(User): nome_empresa = models.CharField(max_length=200) cnpj = models.CharField(max_length=15) def __str__(self): return self.nome_empresa Serializer class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('nome_empresa', 'cnpj') class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'profile') View class usuario(APIView): def patch(self, request, format=None): user = UserSerializer(data=request.data, many=True) if user.is_valid(): user.update(instance=request.user) return Response(HTTP_200_OK) return Response(user.errors) -
Error loading bootstrap on a template
I just installed this app into my django project, http://django-groups-manager.readthedocs.io/en/latest/intro.html However im getting this error when i try and access http://localhost:8000/groups-manager/group/add/ this is the error i get TemplateSyntaxError at /groups-manager/group/add/ 'bootstrap3' is not a valid tag library: Template library bootstrap3 not found, tried django.templatetags.bootstrap3,django.contrib.admin.templatetags.bootstrap3,django.contrib.staticfiles.templatetags.bootstrap3,crispy_forms.templatetags.bootstrap3,allauth.account.templatetags.bootstrap3,allauth.socialaccount.templatetags.bootstrap3,postman.templatetags.bootstrap3 the error seem to lie with {% load bootstrap3 %} Ive added bootstrap3 to my installed apps but no luck. Any ideas? thanks -
broadcast messages to all connected clients in Django websockets
a have a Django chat application using web sockets and channels,the wecbokect connection is establish as you can see here: [mansard@web569 src]$ python3.5 manage.py runserver 22783 Performing system checks... Django version 1.11, using settings 'chatbot.settings' 2017-09-04 16:53:05,478 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-09-04 16:53:05,479 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-09-04 16:53:05,479 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-09-04 16:53:05,480 - INFO - server - HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2017-09-04 16:53:05,480 - INFO - server - Using busy-loop synchronous mode on channel layer 2017-09-04 16:53:05,480 - INFO - server - Listening on endpoint tcp:port=22783:interface=127.0.0.1 [2017/09/04 16:54:09] WebSocket HANDSHAKING /webscok/ [127.0.0.1:42846] [2017/09/04 16:54:09] WebSocket CONNECT /webscok/ [127.0.0.1:42846] chat.js: $(window).load(function() { $messages.mCustomScrollbar(); var ws_path = "/webscok/"; var socket = new WebSocket("ws://" + window.location.host + ws_path); socket.onmessage = function(e) {chatMessage(e.data);} $('.message-submit').click(function() { msg = $('.message-input').val(); socket.send(msg); insertMessage(msg);}); $(window).on('keydown', function(e) { if (e.which == 13) { msg = $('.message-input').val(); socket.send(msg); insertMessage(msg);}}); setTimeout(function() { welcomingMessage();}, 100); }); consumers.py: import json from channels import Channel , Group from channels.auth import http_session_user, channel_session_user, channel_session_user_from_http from channels.sessions import channel_session def ws_connect(message): message.reply_channel.send({"accept": … -
Release Celery lock when transaction is committed
I use a Celery task in my Django project with a lock as described in this article. It works great, but my task creates an object and I don't want that the lock was released before the object is committed in the database. How can I change this context manager to wait until the objects in the task are committed? @contextmanager def lock(lock_id, oid, expire=600): timeout_at = monotonic() + expire - 3 status = cache.add(lock_id, oid, expire) try: yield status finally: if monotonic() < timeout_at: cache.delete(lock_id) @celery.task(bind=True, ignore_result=True) def my_task(self, object_id): with lock('my_task.{}'.format(object_id), self.app.oid) as acquired, transaction.atomic(): if not acquired: self.retry(countdown=1) def on_commit(): # release the lock only in this moment pass transaction.on_commit(on_commit) MyModel.objects.create(object_id=object_id) -
Properly reach Google Cloud SQL via proxy on Bitbucket Pipelines
Whats the proper way to proxy a Cloud SQL Database into Bitbucket Pipelines? I have a Google Cloud SQL Postgres Instance (And also tried a MySQL DB). Opening all ports to connections allows bitbucket pipelines to properly deploy my Django based Google App Engine Project, based off this example pipeline - https://github.com/GoogleCloudPlatform/continuous-deployment-bitbucket/blob/master/bitbucket-pipelines.yml However, when I try to limit the access to the Cloud SQL instances and use cloud_sql_proxy instead, I can properly deploy locally, but Bitbucket will always fail to find the SQL Server My bitbucket-pipelines.yml looks something like this: - export CLOUDSDK_CORE_DISABLE_PROMPTS=1 # Google Cloud SDK is pinned for build reliability. Bump if the SDK complains about deprecation. - SDK_VERSION=127.0.0 - SDK_FILENAME=google-cloud-sdk-${SDK_VERSION}-linux-x86_64.tar.gz - curl -O -J https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/${SDK_FILENAME} - tar -zxvf ${SDK_FILENAME} --directory ${HOME} - export PATH=${PATH}:${HOME}/google-cloud-sdk/bin # Install Google App Engine SDK - GAE_PYTHONPATH=${HOME}/google_appengine - export PYTHONPATH=${PYTHONPATH}:${GAE_PYTHONPATH} - python scripts/fetch_gae_sdk.py $(dirname "${GAE_PYTHONPATH}") - echo "${PYTHONPATH}" && ls ${GAE_PYTHONPATH} # Install app & dev dependencies, test, deploy, test deployment - echo "key = '${GOOGLE_API_KEY}'" > api_key.py - echo ${GOOGLE_CLIENT_SECRET} > client-secret.json - gcloud auth activate-service-account --key-file client-secret.json - wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy - chmod +x cloud_sql_proxy - ./cloud_sql_proxy -instances=google-cloud-project-name:us-west1:google-cloud-sql-database-name=tcp:5432 & - gcloud app deploy --no-promote --project google-cloud-project-name --quiet At this … -
When I add() to a ManyToMany relationship, does it replace the previous records?
I'm creating a set of view for an app that adds and edits teams and volunteers. Volunteers can take part of as many teams as they wish, and a few of them are set as team leaders. Due to the need for flexibility of the process (I guess), I've left both items as separated (I'm open to suggestions on this, though!) and I'm trying to set consistency on the views. For example, I want to make sure that every time I add a team leader on one view, they are also enrolled as a team member. class Team(models.Model): team_name = models.CharField(max_length=30, null=True, blank=True) leaders = models.ManyToManyField(Volunteer, related_name='leaders', blank=True) enrolled = models.ManyToManyField(Volunteer, related_name='enrolled', blank=True) class Volunteer(models.Model): name = models.CharField(max_length=30) I have a view on which I'm doing just this. After saving the form, I take each of the leaders and add them to the enrolled field. However, when I add them, I find that the previous values of enrolled on the field has been replaced by the new values I added. I could just save the previous values in a variable and reapply, but is it supposed to work this way? class TeamUpdate(LoginRequiredMixin, UpdateView): form_class = TeamCreateForm model = Team def … -
Highchart graph not displaying via Django
I've been trying to display a Highchart graph via Django, but in vain. See below, the hmtl code I get from the view source mode from my browser... The graph dataset is passed on nicely and shows up in the code, but the graph doesn't show up on the page and I get no errors from the javascript console. What am I missing here? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Highcharts- Demo</title> <style> body{ margin-top: 30px; margin-left:40px; } pre { border:1px solid red; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="http://code.highcharts.com/highcharts.js"></script> <script src="http://code.highcharts.com/modules/exporting.js"></script> </head> <body> <div style="width: 800px; margin: 2em auto; padding: 1em; border: 1px solid red; border-radius: 0.5em"> Nicely plotted data in Highcharts. </div> <div id="chart_ID" class="chart" style="height:600px; width:100%"> </div> <!-- Maps the Python template context variables from views.py to the Highchart js variables --> <script> var chart_id = "chart_ID" var chart = {"renderTo": "chart_ID", "type": "line", "height": 500} var title = {"text": "my title goes here"} var xAxis = {"categories": ["A", "B", "C", "D", "E", "F", G"], "title": {"text": "Axis title goes here"}} var yAxis = {"title": {"text": "Axis title goes here"}} var series = [{"data": … -
djang not able to access jsonfield data in templates
Actually, I don't know how to access jsonfield data in the template. I tried something like this {% for key in place.places_to_visit %} {{ key }}:{{ value }} {% endfor %} But it is showing all json data that I have added including {} and " " and also for Arrayfield of characters And also I want to add an image in that jsonfield how to do that? Does that image need to be media directory and then I should include its path? Or some other ways to do that? And it is also giving error as "[05/Sep/2017 23:03:00] "GET /ontheway/1/ HTTP/1.1" 200 4238" Thank you in advance -
Django: How is <classname>_set attribute created in models.Model subclass?
In Django, I can have a model Question and a model Choice: class Question(models.Model): ... def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) ... def __str__(self): return choice_text I can then do this: >>>q = Question(question_text = 'How are you?', pub_date = timezone.now()) >>>q.choice_set.all() <QuerySet []> The q.choice_set, according to my understanding, accesses the set of Choice objects in our database which refer to q by their foreign key. My question is: How is the choice_set attribute being created? I've never seen a attribute name taking the name of another class in lower case letters. How is this achieved? -
Create Permission without a ContentType model
Is there a way I can create a permission without a ContentType, or somehow set it to django.db.models.Model? This is what I currently have (in a migration): ContentType = apps.get_model("contenttypes", "ContentType") Model = apps.get_model("models", "Model") <-- doesn't work, can't find an app labeled 'models' Permission = apps.get_model("auth", "Permission") content_type = ContentType.objects.get_for_model(Model) Permission = ..... So maybe a better question would be "why it can't find the Model model?" -
getting data from 3 tables that related to each other and displaying them in template - django
i want to implement a survey in my site. i created 3 tables for that. the followings are the code of each model: class Survey(models.Model): klass_id = models.ForeignKey(Klass, verbose_name='class', related_name='s_klass', on_delete=models.CASCADE) question = models.CharField(max_length=100, verbose_name='title') description = models.CharField(max_length=500, verbose_name='description', blank=True, null=True) end_date = models.DateTimeField(verbose_name='end date') class SurveyOptions(models.Model): survey_id = models.ForeignKey(Survey, verbose_name='survey name', related_name='s_id', on_delete=models.CASCADE) text = models.CharField(max_length=50, verbose_name='option title') class SurveyResponse(models.Model): option_id = models.ForeignKey(SurveyOptions, verbose_name='option name', related_name='s_option', on_delete=models.CASCADE) person_id = models.ForeignKey(Profile, verbose_name='responser', related_name='responser', on_delete=models.CASCADE) create_date = models.DateTimeField(verbose_name='date', auto_now_add=True) after users response to the survey, i want to get survey results and display them to users. in template, i want to show survey question, survey options and survey responses( each option and its percent). what do i write in views.py and what do i write in template? the Klass in the first model refers to a model. and when i go to page related to each Klass, i must see all surveys of the Klass. Klass refers to university classes. -
pushing django migrations into source control
I've deployed my Django application for a while now, but all this time I've kept migrations out of souce control. What I did was run makemigrations and migrate twice-- once in development, and once in production. So now how can I seamlessly put my migrations into source control? Theoretically the migrations should be the same (given my models.py files haven't changed), but how would I go about matching my migrations up without accidentally overriding something? -
Django: Display image from database in DetailView template
I am trying to display all of a user's info on their profile page. This includes their profile picture, however I can't get the image to display. I think everything is right, I've found some stuff on this and I have tried to match it up respectively, however I' clearly missing something. Here is my code: Model: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from users.choices import * # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User) join_date = models.DateTimeField(default=timezone.now) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) location = models.CharField(max_length=150) title = models.CharField(max_length=250) user_type = models.IntegerField(choices=USER_TYPE_CHOICES,default=1) website = models.URLField(max_length=100,blank=True) about = models.TextField(max_length=500,default='about') twitter = models.CharField(max_length=50,blank=True) dribbble = models.CharField(max_length=50,blank=True) github = models.CharField(max_length=50,blank=True) def __str__(self): return self.user.username UserProfileView: class UserProfileView(DetailView): model = UserProfileInfo Profile Template (userprofileinfo_detail.html): {% extends "base.html" %} {% block content %} <div class="sidebar-userinfo"> <img class="profile-pic" src="{{ userprofileinfo.profile_pic.url }}"> <h2>{{ userprofileinfo.username }}</h2> <p class="accent">Score:</p> <p>Score goes here</p> <form> <button type="submit">Follow</button> </form> <p class="accent">Title:</p> <p class="profile-info">{{ userprofileinfo.title }}</p> <p class="accent">Website:</p> <p class="profile-info">{{ userprofileinfo.website }}</p> <p class="accent">I'm a:</p> {% if userprofileinfo.user_type == 1 %} <p class="profile-info">Designer</p> {% elif userprofileinfo.user_type == 2 %} <p class="profile-info">Designer</p> {% else %} <p class="profile-info">Both</p> {% endif %} <p class="accent">About Me:</p> <p class="profile-info">{{ userprofileinfo.about }}</p> <p … -
After saving form data in django I loose my data when saving to new table field
When I make a payment the data gets saved in the payments model in django. Then i would like to save the data from the form in the bookings model and also in the earnings model. The data saves in the payfast model but then seems to loose my data. Below is all 3 models, Data that gets sent and my view logic Payfast model class PayFastOrder(models.Model): # see http://djangosnippets.org/snippets/2180/ __metaclass__ = readable_models.ModelBase # Transaction Details m_payment_id = models.AutoField(primary_key=True) pf_payment_id = models.CharField(max_length=40, unique=True, null=True, blank=True) payment_status = models.CharField(max_length=20, null=True, blank=True) item_name = models.CharField(max_length=100) item_description = models.CharField(max_length=255, null=True, blank=True) amount_gross = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) amount_fee = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) amount_net = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) # The series of 5 custom string variables (custom_str1, custom_str2...) # originally passed by the receiver during the payment request. custom_str1 = models.CharField(max_length=255, null=True, blank=True) custom_str2 = models.CharField(max_length=255, null=True, blank=True) custom_str3 = models.CharField(max_length=255, null=True, blank=True) custom_str4 = models.CharField(max_length=255, null=True, blank=True) custom_str5 = models.CharField(max_length=255, null=True, blank=True) # The series of 5 custom integer variables (custom_int1, custom_int2...) # originally passed by the receiver during the payment request. custom_int1 = models.IntegerField(null=True, blank=True) custom_int2 = models.IntegerField(null=True, blank=True) custom_int3 = models.IntegerField(null=True, blank=True) custom_int4 = models.IntegerField(null=True, blank=True) custom_int5 = models.IntegerField(null=True, … -
I'm wondering what I can do to improve this full-text search code in my Django app
The code works such as it is, but I'm have feeling I'm building the query incorrectly. def search_results(request): terms = request.GET['search_terms'].split() vector = SearchVector('title', 'subtitle', 'header_image', 'header_image_caption', 'excerpt', 'body', 'tags__name',) query = SearchQuery('') for term in terms: query = query | SearchQuery(term) results = Article.objects.annotate(search=vector).filter(search=query).order_by('-pub_date',).distinct('pub_date',) return render(request, 'etherblog/search_results.html', context={'articles': results, 'terms': terms}) Also getting this error triggered by search engines I believe: File "/home/danjewett/webapps/ether/ether/etherblog/views.py" in search_results 102. terms = request.GET['search_terms'].split() File "/home/danjewett/webapps/ether/etherenv/lib/python3.5/site-packages/django/utils/datastructures.py" in __getitem__ 85. raise MultiValueDictKeyError(repr(key)) Exception Type: MultiValueDictKeyError at /search_results/ Exception Value: "'search_terms'" Request information: USER: AnonymousUser -
DjangoRestFramework with Oracle an no id field
I'm trying to get Django Rest Framework (3.6.4) running with a simple model. However, the model does not contain an ID field so I'm getting django.db.utils.DatabaseError: ORA-00904: "HCM_JOBS"."ID": invalid identifier The PK is going to be a composite of three fields in the model. I tried setting a custom id field in my serializer via class HcmJobsSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField(source="HcmJobs.position") class Meta: model = HcmJobs fields = '__all__' but I still get the same ORA-00904 error from it trying to get an id field. Most of what I've found on StackOverflow has been on how to deal with the id field, not how to deal with not having one. I don't have control over the tables themselves so I can't add in an id field. Any idea how I can use the framework without an ID field?