Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TODO List with Pycharm
I want to create TODO Project. Project has a textbox and button. when you fill the textbox and press button. This todo add following list. I can list database info but I couldn't insert. How can I save new todo from html tamplete ? view.py : from django.shortcuts import render from django.http import HttpResponse, JsonResponse from models import Todo from django.db import models def dummy(request): todos = Todo.objects.all() return render(request, "dummy.html", {"todos": todos}) def save(): **\ I want to add this line save database code models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Todo(models.Model): user = models.ForeignKey(User) todo = models.CharField(max_length=120) created_at = models.DateTimeField(auto_now=True) deadline = models.DateTimeField() def __str__(self): return ("%s of %s") % (self.todo, self.user.username) def __unicode__(self): return self.__str__() my html tamplate dummy.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form> <a>Please Enter Your Task</a><br><br> <input name="todoText"><br><br> <input type="submit" value="Save Task"></input> <br><br> </form> <div> {% for todo in todos %} <div> <h1>{{ todo.user.username }}</h1> <h2>{{ todo.todo }}</h2> </div> <hr /> {% endfor %} </div> -
django and jqgrid not using django-jqgrid
I've been having trouble implementing the above jquery plugin with django. when I request from html ,always took the error: SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data. Somebody help me please,thanks a lots! See below for code references. model: class CustomersInfo(models.Model): name = models.CharField(max_length=20) sexuality = models.CharField(max_length=4) age = models.IntegerField(default=0) telphone = models.CharField(max_length=20) webchat = models.CharField(max_length=20) birthday = models.DateTimeField('date birth') method = models.CharField(max_length=20, default='friends') note = models.CharField(max_length=50) def __str__(self): return self.name urls: url(r'^login/$', views.login_ace, name='login'), url(r'^register/$', views.register, name='register'), url(r'^customer/$', views.customer, name='customer'), view: def customer(request): model = CustomersInfo csts = [] custominfo = model.objects.all() for i in custominfo: cst = {'id': i.id, 'name': i.name, 'sexuality': i.sexuality, 'age': i.age, 'telphone': i.telphone, 'webchat': i.webchat, 'birthday': i.birthday.date(), 'method': i.method, 'note': i.note} csts.append(cst) if request.method == 'GET': # return JsonResponse(csts, safe=False) j = json.dumps(csts, ensure_ascii=False, cls=DjangoJSONEncoder) return render(request, 'skincrm/customer.html', {"grid_data": j}, content_type='application/json') else: return render() by the way,variable j's values : [{"webchat": "13540137317", "age": 39, "method": "friends", "telphone": "13540137777", "birthday": "2017-03-16", "sexuality": "male", "note": "my side", "name": "tom", "id": 1}, {"webchat": "13882025256", "age": 30, "method": "friends", "telphone": "13882025555", "birthday": "2017-03-02", "sexuality": "female", "note": "my side", "name": "jerry", "id": 2}] html: jQuery(grid_selector).jqGrid({ url:"{% url 'skincrm:customer' %}", mytype:"GET", datatype: "json", height: … -
Django Rest Api with Pandas
I am using django-rest-framework to make an api of my data. I am making an app that takes into account user data and remove outliers from that data using Pandas. I am able to present my data on frontend using django templates but somehow I am not able to make an API containing the statistical data using django-rest-framework . Can someone explain it and please help me to rectify my errors and also provide the necessary code Here is my code class Data(models.Model): Name = models.CharField(max_length=30,null=True,blank=True) Age = models.IntegerField(null=True,blank=True) Weight = models.FloatField(null=True,blank=True) Height = models.FloatField(null=True,blank=True) Sugar = models.FloatField(null=True,blank=True) def __unicode__(self): return self.Name My Serializer Class class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = '__all__' my views.py def my_view(request): con = sqlite3.connect("db.sqlite3") df = pd.read_sql_query("SELECT * from visualapp_health", con) a = df.fillna(0) a['x-Mean'] = abs(a['Age'] - a['Age'].mean()) a['1.96*std'] = 1.96*a['Age'].std() a['Outlier'] = abs(a['Age'] - a['Age'].mean()) > 1.96*a['Age'].std() con.close() return render(request, 'visual.html', {'visual': a}) I am able to get all the Data when using Django templates but somehow I don't able to understand how to make an API of all the data using django-rest- framework. -
Uncaught SyntaxError: Unexpected token ILLEGAL Jquery
I know there are a lot of questions on this issue. But I want to know if there are any alternatives to solve this issue. PROBLEM: I want to fetch existing text in database tables and put it in Textarea in HTML. I am using Django framework. $("textarea[name=profileitemdescription]").val("{{item.item_description}}"); the above code works when there are no line breaks /n in {{item.item_description}}. It puts value in Textarea if the value({{item.item_description}}) is a single line. Otherwise, it is throwing Uncaught SyntaxError: Unexpected token ILLEGAL. Any workaround to put value({{item.item_description}}) in Textarea ? -
German letter 'ü' lost in translation in Django web application
In our Django web project we use german translations from a '.mo' file. One of the translation words as follows. msgid "Back" msgstr "Zurück" This is used in text field of buttons. What I get in button is '<span class="button">Zurck</span>' instead of 'Zurück' In other translation texts letter 'ü' is used many times and does not get missing but only this one 'ü' gets lost. What can be the problem here? -
Dynamic query url order django
Is there a way to match url to get result based on dynamic queries in Django without having to declare multiple urlpatterns. What I mean is the same urlpatterns to match something like localhost:8000/person/?name=john&age=10&gender=male localhost:8000/person/?age=10&gender=male&name=john localhost:8000/person/?gender=male&name=john&age=10 -
Django displaying images
Hey i'm new in django/python and i'm trying to create a project and i got a problem with displaying image after submit button. I'm trying to make table with checkboxes and the ones i select would be displayed in next page but I get only blank paper or i can see image name, could anyone help me? Example Here is my code: index.html {% extends 'tag/base.html' %} {% block title %}Tags{% endblock %} {% block body %} <script language="JavaScript"> function toggle(source) { checkboxes = document.getElementsByName('selected'); for(var i=0, n=checkboxes.length;i<n;i++) { checkboxes[i].checked = source.checked; } } </script> <form action="{% url 'tag:selected' %}" method="get" name="selected" enctype="multipart/form-data"> <table class="white-table table-bordered table-hover" style="width:95%; margin: 3% auto;"> <thead> <tr> <th style="text-align:center;"><input type="checkbox" onClick="toggle(this)"></th> <th></th> <th style="text-align:center;">Name</th> <th style="text-align:center;">Chip Type</th> <th style="text-align:center;">Size</th> <th style="text-align:center;">Frequency</th> <th style="text-align:center;">Memory</th> <th style="text-align:center;">Reading distance</th> <th class="null" style="text-align:center;">Environment</th> <th class="null" style="text-align:center;">Mounting method</th> </tr> </thead> <tbody> {% for tags in all_tags %} <tr> <td style="text-align:center;"><input type="checkbox" id="{{ tags.id }}" name="selected" value="{{ tags.tag_image.url }}"></td> <td><a href="{% url 'tag:detail' tags.id %}"> <img src="{{ tags.tag_image.url }}" name="pic" class="img-responsive" style="width: 60px; height:80px; margin:auto;" /> </a></td> <td style="text-align:center;"> {{ tags.tag_name }} </td> <td style="text-align:center;"> {{ tags.tag_chip_type }} </td> <td style="text-align:center;"> {{ tags.tag_size }} </td> <td style="text-align:center;"> {{ tags.tag_frequency }} … -
Unable to understand a line from the django tutorial
I am working on the official Django tutorial at https://docs.djangoproject.com/en/1.10/intro/tutorial03/ . I am unable to understand this line. Could someone please break it down for me? Question.objects.order_by('-pub_date')[:5] output = ', '.join([q.question_text for q in latest_question_list]) -
How could I implement saving priority to the model in ORM and later getting object with the highest priority in view?
I'm building application with Django but got a problem with django ORM . We have a model related to some user. I later need to get all object of this model in view with the highest priority. So if I have to same objects, I need to get one with highest priority. How could I implement saving priority to database and later getting object with the highest priority in view? It must must be so simple, but I have no idea -
IntegrityError: (1062, "Duplicate entry 'email@outlook.com' for key 'username'")
I have a little issue. It displayed the error IntegrityError: (1062, "Duplicate entry 'email@outlook.com' for key 'username'") The part of the models looks like @python_2_unicode_compatible class EmployerProfile(AbstractAddress): customer = models.OneToOneField( CustomerProfile, verbose_name=_('Customer'), related_name='employerprofile') company_name = models.CharField(_('Company name'), max_length=50, blank=True, < #That function will empty all fields in this model whenever income_source # is different of 'Employed' def empty_fields(self): to_empty = [f.name for f in EmployerProfile._meta.get_fields()] exclude = [u'id', "has_missing_fields", "manual_validation", "actor_actions", "target_actions", "action_object_actions", ] for field_name in to_empty: if field_name not in exclude: setattr(self, field_name, None) def __str__(self): if hasattr(self, 'customer'): u = self.customer.user else: u = _('Uninitialized') return six.text_type(_("%s's employer profile") % u) @python_2_unicode_compatible class FinancialProfile(models.Model): customer = models.OneToOneField( CustomerProfile, verbose_name=_('Customer'), related_name='financialprofile') income_source = models.CharField(_('Income source'), max_length=20, choices=settings.LOANWOLF_INCOME_SOURCE_CHOICES, default='employed') From the signals.py file #We clean fields from EmployerProfile with clean_fields() method if income_source != 'Employed' @receiver(post_save, sender=FinancialProfile, dispatch_uid="customers.employerprofile.empty_fields") def invalidate_employer_profile(sender, instance, **kwargs): print(instance.income_source) if instance.income_source != u'employed': employer_profile = instance.customer.employerprofile employer_profile.empty_fields() employer_profile.save() From the traceback of django Traceback (most recent call last): File "/home/jeremie/Projects/credit-django/venv/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/home/jeremie/Projects/credit-django/venv/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 170, in __call__ response = self.get_response(request) File "/home/jeremie/Projects/credit-django/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 124, in get_response response = self._middleware_chain(request) File "/home/jeremie/Projects/credit-django/venv/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = response_for_exception(request, exc) … -
Django Python, javascript will not send requests - very simple code
I've been trying to send a variable through JS in HTML using my views url. I have a super super simple API which looks like this (views.py). As you can see it literally takes anything in and slaps it into the updated field. So if you were to visit that page it shows the last thing posted. def store(request): req = str(request) l=len(req) if l > 28: Storage.objects.last().delete() q = Storage(data=req[26:l-2]) q.save() link = Storage.objects.last() return render_to_response('crophop/imgur.html',{'link':link}) I have then done this to pass the number 100, for the webpage to store it. <script>var URL = "{% url 'store' %}"</script> <html stuff....> <script> $.get(URL, '100', function(response){ if(response === 'success'){ alert('Yay!'); } else{ alert('Error! :('); } }; </script> I've tried so many versions of this, I don't know why js wont comply. I know I can't access external URLs easily so I thought this was the best way. I've seen many posts on this and tried as many as I found but I'm still stuck... If anyone has any ideas why this doesn't work I'd be grateful. It seems like it's so basic it should work, it might be something to do with pythonanywhere.com? Thanks, Fred -
how to pass a Dictionary value from view to template in django application
I am just trying to learn a django project. I already did the creation of project and inside project myapp using django command. In the directory /myproject/myapp$ I have views.py file. Another directory /myproject/myapp/templates$ I have hello.html file. I want send a Dictionary value from views.py file to hello.html file using render function. But I am getting some error called Internal Server Error: /hello/ Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/joy/pythonWork/myproject/myapp/views.py", line 8, in hello name : 'xyz', NameError: global name 'name' is not defined My file are listed bellow: /views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def hello(request): personalDetails = { name : 'xyz', phoneno : '7022924374' } return render(request, "hello.html", {personalDetails}) /hello.html <html> <body> <h1>Hello</h1>{{personalDetails}} </body> </html> -
Deploying a Django application with Apache on Ubuntu 16.04
I have been striking my head against an application to be deployed on an Apache server using Ubuntu 16.04. I thought may be it's a misconfiguration issue in my site, so just deployed a test app test_deploy and following the very basic instructions on Django documentation and here's what I inserted in my /etc/apache2/sites-available/000-default.conf: WSGIScriptAlias / /home/faizan/python/test_deploy/test_deploy/wsgi.py WSGIPythonHome /home/faizan/python/test_deploy/venv WSGIPythonPath /home/faizan/python/test_deploy/ <Directory /home/faizan/python/test_deploy/test_deploy> <Files wsgi.py> Require all granted </Files> </Directory> And, I can't see anything on localhost. Am I doing configurations right? -
How to query record from database with datatype?
I need to get the data from models according to datatype. Is it possible get data from models by it's field data type not by column name's. For example: In my database I created sample1 and sample2 tables. sample1 fields: name(CHAR), file(BINARY), division(INT) sample2 fields: set(INT), basefile(BINARY) I have selected models dynamically from front end page.Now I want to get records which records having binary data from the selected model,whatever its field name. Is it possible? any help appreciated. Thanks in advance. -
Django request not defined
I am trying to implement an Http server and have the following line of code in my program if request.method == 'GET' I keep getting a NameError that request is not defined. Here are my imports from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from rest_framework import status from people.models import People from people.serializers import PeopleSerializer I can not figure out why request is said to be not defined when it is a valid object in Http which i have imported. -
html content is not sent in email
I want to sent the link to the email so when user clicks that link, the user will be redirected to the refer page and can refer other friends. I have used send_mail to send the email. Everything gets sent except the html message. Here is what i have done if created: new_join_old.invite_code = get_invite_code() new_join_old.save() subject = "Thank you for your request to sign up our community" html_message = '<a href="http://localhost:8000/{% url "invitations:refer-invitation" invite_code %}">Click Here</a>' message = "Welcome to Connyct! We will be in contact with you." from_email = None to_email = [email] send_mail(subject, message, from_email, to_email, fail_silently=True, html_message=html_message) messages.success(request, '{0} has been invited'.format(email)) return HttpResponseRedirect("/invitations/refer-invitation/%s"%(new_join_old.invite_code)) context = {"form": form} return render(request, 'home.html', context) -
how to show data from joined tables in DJANGO DRF
I'm trying to show data from a table that has several ForeignKey fields assigned to it: class Promotion (models.Model): User = models.ForeignKey(User) Rating = models.ForeignKey(Rating) Date_Effective = models.DateField() def __str__(self): return self.Rating.Rank.Short_Rank + ' ' + self.User.last_name + ' (' + str(self.Date_Effective) + ')' class Rating (models.Model): Rank = models.ForeignKey(Rank) Genre = models.ForeignKey(Genre) Branch = models.ForeignKey(Branch) Image = models.FileField(upload_to='ranks') def __str__(self): return self.Rank.Display_Rank + " (" + self.Branch.Branch + "; " + self.Genre.Short_Term + ")" I'm trying to build a serializer that shows the Rating.str value from it and User information. class PromotionSerializer(serializers.HyperlinkedModelSerializer): Rating = serializers.PrimaryKeyRelatedField(many=True, read_only=True) users = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Promotion fields = ('Date_Effective', 'Rating', 'users') This results in error: Exception Type: TypeError at /member/api/promotions/ Exception Value: 'Rating' object is not iterable I'm trying to figure this thing out. How do I do this? Thanks much. -
django KeyError: "'__name__' not in globals"
I've created an model Girl When I open python console and write from .models import Girl I get an error: >>> from .models import Girl Traceback (most recent call last): File "<console>", line 1, in <module> KeyError: "'__name__' not in globals" What do I do? -
Creating a 'backwards' relationship between two model objects in Django
In Django, I'm using @receiver to save a model object named CampaignProfile like so: @receiver(post_save, sender=UserModel) def save_campaign(sender, instance, created, **kwargs): if created: instance.CampaignProfile.save() I've created a custom user model named UserModel which needs to be linked with the CampaignProfile model, where the CampaignProfile looks something like this... class CampaignProfile(models.Model): user = models.ForeignKey(UserModel, related_name='CampaignProfile', on_delete=models.CASCADE, null=True) campaign_title = models.CharField(max_length=50, verbose_name='Title') However when I try to create a new super user through the Terminal then I get an error like so... AttributeError: 'RelatedManager' object has no attribute 'save' Does anybody know why creating a new super user would bring up this sort of error? Thanks. -
Django: Which characters are escaped by render_to_response?
Which characters are escaped by Django's render_to_response()? I have seen: &lt; < &gt; > &quot; " &amp; & &#39; ' I'm looking for a complete list. (I think the ones above are the only ones that are strictly necessary...?) -
Display list of fields from a class from another
I know we could easily display a list of all fields from a particular class, e.g. EmployerProfile, with [f.name for f in EmployerProfile._meta.get_fields()] Assume that have another class, e.g. FinancialProfile, and which both classes doesn't derive from each other. I would like from this specific class to access the fields from the other class. I mean I would like to create a list of fields from EmployerProfile from inside FinancialProfile. How could I do such thing? Is super() method is a great way to do this? -
Return only one json object with the highest priority . Tastypie + Django
Trying to figure out Tastypie tricks but it'a not so obvious to me how to do the following. Lets say we'v got a model class UISettings(models.Model): setting_bool = models.BooleanField(default=True) setting_float = models.FloatField(null=True, blank=True, default=None) setting_string = models.CharField(max_length=10000) setting_json = models.CharField(max_length=10000) setting_integer = models.IntegerField() user = models.ForeignKey(User) CROSS_SETTINGS_RELATION = ( ('OC', 'One company related'), ('AC', 'Any company related'), ('AA', 'All employee any company related '), ) c_relation = models.CharField( max_length=2, choices=CROSS_SETTINGS_RELATION, default='AA', ) And resource in api: class UserResource(ModelResource): campaign = fields.ForeignKey(CampaignResource, 'campaign') class Meta: queryset = User.objects.all() resource_name = 'user' allowed_methods = ['get'] class UISettingsResource(ModelResource): user = fields.ForeignKey(UserResource, 'user') class Meta: queryset = UISettings.objects.all() resource_name = 'uisettings' allowed_methods = ['get','post'] authorization = Authorization() I need to return UISettings object for user BUT if there are several similar objects I need to return the one with the higher priority like AA is the most important , AC second importance and OC the last. So I if there few same object I need to return only one json object with the highest priority. Any ideas how could I implement that? CROSS_SETTINGS_RELATION = ( ('OC', 'One company related'), ('AC', 'Any company related'), ('AA', 'All employee any company related '), ) -
Django model objects, admin and javascript files
I have a problem with objects in django admin. I have a model: class Group(models.Model): name = models.CharField(max_length=30) description = models.TextField() pay = models.CharField( max_length=10, choices=(('PAID', 'PŁATNY'), ('FREE', 'DARMOWY')), default='FREE') time = models.CharField( max_length=3, choices=(('T', 'TAK'), ('N', 'NIE')), default='N', help_text='Czy wpis ma być wyłączony po jakimś czasie czy bezterminowy') days = models.IntegerField(default=1) premium_box = models.CharField( max_length = 3, choices=(('T', 'TAK'), ('N', 'NIE')), default='N', help_text='Czy wpis ma być wyświetlany w okienku reklamowym') category = models.CharField( max_length = 2, choices=(('1','1'), ('2','2')), ) def __str__(self): return self.name For now I have 2 group objects: free and premium. How can I use value of those objects in my javascript file? I need something like this: if (GROUP.OBJECT.CATEGORY < 2) { $("div > fieldset > div.form-row.field-category1").hide(); $("div > fieldset > div.form-row.field-subcategory1").hide(); $("#group").html('<ul><li>- Additional text</li>'); } if (GROUP.OBJECT.TIME == 'N') { $(SOME.FIELD).hide() } Is it possible in Django? -
Displaying check mark and cross instead of boolean TRUE and False??
I have a Django/MySQl/bootsrap website where my view displays some boolean column values. Is there a way to display check mark and cross mark instead of showing TRUE or False? It can either be a .svg file or HTML code for check mark and cross. Any brilliant mind around has done the same? -
NoReverseMatch at
I have this error and I do not find solution, I get the keywords of ID_pedido_ex and cod_experto but I still throw the error, student help please? Reverse for 'entregado_ex' with arguments '()' and keyword arguments '{'id_pedido_ex': 11, 'cod_experto': 'VA-0012 '}' not found. 1 pattern(s) tried: ['solicitar/entregar-extra/(?P<id_pedido_ex>\\d+)/(?P<cod_experto>\\d+)/$'] Error during template rendering. button Template html: <a href="{% url "usuario:entregado_ex" id_pedido_ex=ex.id cod_experto=ex.articulo_ex.cod_experto %}" method='GET' type="submit" class="btn btn-success pull-right"/>Entregar</a> url global: urlpatterns = [ # Examples: url(r'^solicitar/', include(urls, namespace="usuario")), ] url app: urlpatterns = [ url(r'^entregar-extra/(?P<id_pedido_ex>\d+)/(?P<cod_experto>[\w-]+)/$', Update_stockex, name="entregado_ex"), ] views.py: @login_required def Update_stockex(request, id_pedido_ex, cod_experto): if request.method == 'GET': pedido = Pedido_Extra.objects.get(id=id_pedido_ex) articulo = Articulo.objects.get(pk=cod_experto) articulo.stock -= pedido.cantidad_ex articulo.save() pedido.estado_ex = 'entregado' pedido.fecha_entrega_ex = datetime.now() pedido.save() return HttpResponseRedirect('/solicitar/pedidos-extra/') What is the problem? regards!