Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How should I write test code?
I wrote test code in tests.py like this: #coding:utf-8 from django.test import TestCase from app.models import User # Create your tests here. class UserModelTests(TestCase): def setUp(self): self.user1 = User.objects.create(name='Tom', group = 'A',age=20,rank=1) def test_user1_name(self): self.assertEqual(self.user1.name, 'Tom') def test_user1_group(self): self.assertEqual(self.user1.group, 'A') def test_user1_age(self): self.assertEqual(self.user1.age, 20) def test_user1_rank(self): self.assertEqual(self.user1.rank, 1) But I thought my test code is meaningless. Arguments Data.objects.create has is really in db. How should I write it to compare the db results and value I want to compare for the test? -
Forbidden (CSRF token missing or incorrect.) Django how to solve?WITH MY CODE
when i press button, this error is blow up Forbidden (CSRF token missing or incorrect.): /orders/basket_adding/ / I take csrf_token from the form on the main page, all the others inherit from the page where the form is, from where I get the token! Pls help me) views def basket_adding(request): print('HER') return_dict = {} session_key = request.session.session_key data = request.POST context = {} return JsonResponse(return_dict) ///// ///// html {% extends "base.html" %} {% load staticfiles %} {% block content %} <div class="single"> <div class="container"> <div class="single-main"> <div class="single-top-main"> <div class="col-md-5 single-top"> <div class="flexslider"> <ul class="slides"> {% for img in images %} <li data-thumb="{{ img.image.url }}"> <div class="thumb-image"> <img src="{{ img.image.url }}" data-imagezoom="true" class="img-responsive"> </div> </li> {% endfor %} </ul> </div> </div> <div class="col-md-7 single-top-left simpleCart_shelfItem"> <h2>{{ product_himself.brand.name_of_brand }}</h2> <h1 class="product_name" action="{% url 'orders:basket_adding' %}" >{{ product_himself.name_of_product }}</h1> <p class="hidden product_id">{{ product_himself.id }}</p> {% if product_himself.discount %} <span>$<strike>{{ product_himself.price_of_product }}</strike>&nbsp;&nbsp;$<span class="item_price">{{ product_himself.price_with_discount }}</span></span> {% else %} $<h6 class="item_price">{{ product_himself.price_of_product }}</h6> {% endif %} <p>{{ product_himself.description }}</p> <h4>Size</h4> <ul class="bann-btns"> <li><select class="bann-size"> <option value="s">Small</option> <option value="m">Medium</option> <option value="l">Large</option> </select> </li> <li><a href="#" class="item_add">Add To Cart</a></li> </ul> </div> <div class="clearfix"> </div> </div> <div class="singlepage-product"> {% for smart in img_bran %} <div class="col-md-3 home-grid"> … -
Change a Django Model with Javascript
So i want to change the Django Module to +1 everytime someone presses the button without reloading the Page. I think its called Ajax. JS: $('.buttonclass').click(function(){ var pk; pk = $(this).attr("data-pk"); }); html: <span data-pk="{{post.pk}}" class="buttonclass"></span> my_views.py def upvote(request): pk = None if request.method == 'GET': pk = request.GET['pk'] obj = models.Post.objects.get(pk=pk) obj.upvotes = obj.upvotes +1 obj.save() return redirect("index") #without this post: class Post(models.Model): upvotes = models.IntegerField(default = 0) So how exactly can i do this? -
replace url in Django template
{% if shelf.script or shelf.log_url %} {% if shelf.log_url %} Log URL: {{ shelf.log_url }}<br /> {% endif %} {% if shelf.log_url %} <b>Another URL:</b> {{ shelf.log_url.replace("/tmp/BOOTLOG/", "http://www.sxp.com") }}<br /> {% endif %} {% endif %} I have already got a log url, I would like to update this url with with a domain address and adding /index.html to at the end. I would like to replace this url shelf.log_url output = /tmp/BOOTLOG/darwin_12345.tgz to something like this. www.sxp.com/darwin_12345/index.html How can I do in Django template ? -
Cannot run PyDev : Django when running with Eclipse Oxygen
New to Python (just learning it). I have the following setup on Windows 10: Python 3.6.2 (pip 9.0.1), Django 1.10 Eclipse IDE and PyDev IDE for Eclipse 6.0.0 (installed using Eclipse Marketplace under Eclipse Oxygen). I had chosen this combination because I wanted to be able to debug any code that was developed. I have created a Django Project (New -> PyDev Djangon) with the settings in the attachment I used the following settings with DJango itself because my goal is to use REST APIs for DB access (and not access the DB directly) - I wanted to use the REST functions with Android apps as well. When doing "right-mouse-click: ProjectName -> PyDev: Django", the internal website does not come up. Why is this the case? When looking for a combination of "Eclipse", "PyDev", "DJango" (to seek out an answer), I see articles that are 2 years old or older. Does anyone use this way of developing web applications under Python anymore? If not, is there a better option? TIA -
django oscar dashboard default credentials
I would like to know whats Django's Oscar dashboard default credentials. (since I couldn't enter it). In addition, Is there any alternative more recommended for Django e-commerce? Thank you. -
How to test import image into cloudinary with django?
I started creating django unit tests for my project referring to the django documentation. But in my case I can't find documentation on how to test an upload of a picture into cloudinary, how to know if the import is succeeded. I have created this unit test to test the upload of a picture : def test_upload_profile_picture(self): url = self.reverse('save_profile_picture') img = '/images/img.jpg' self.client.login(username=self.username, password=self.password) with open(img, 'rb') as infile: response = self.client.post(url, {'picture': infile}) self.assertRedirects(response, self.reverse('edit_profile')) But I guess this is not correct since I really don't know if the image is really uploaded to cloudinary or not . Has someone an idea about how to do this ? Thanks in advance. -
django-statsy seem to be a doubtful app
I have a bit of difficulties to understand how django-statsy works. Does anyone be able to tell me if it works well for them? I am a new programmer in Django and using the template, but it is unclear that we could use the following structure in a .html template : var statsy = new Statsy() statsy.send({ 'group': 'post', 'event': 'subscription' }); Am I right? Otherwise, how could we use that code in a .html file? Could anyone be able to tell me what is this writing, because I am not familiar with it? -
Unable to re-authenticate evernote
This is a bit embarrassing. Several years ago I set up some productivity scripts in python etc on the evernote production sdk. My authentication token expired today and the method I was using (PHP) to get a token has stopped working on my server. Yes, I used PHP to get the token and python to do the work. That's a long story in itself. Anyway I got a django instance up and running and can get the evernote sample script listing my production notebooks. But how do I grab the actual authentication token so I can store it and deploy it into my scripts? Sorry for asking such a dumb question but I'm too busy to dig at the moment and I need to access those scripts! -
Django REST framework HyperlinkedModelSerializer
I'm working on streamlining how I include different models in the API for my Djangp app. Previously I had it set it where each model had a Viewset and a Serializer separately defined for it. Instead I'm working on a more generic method whereby I just pass in a Model and a list of relevant fields, and will be added to the API automatically. The problem I'm running in to currently is with defining the serializer_class: from myapp import MyModel from rest_framework.serializers import HyperlinkedModelSerializer from rest_framework.viewsets import ModelViewSet app_name = 'myapp' fields = ('field1', 'field2', 'field3') queryset = MyModel.objects.all() # Problem is here serializer_class = HyperlinkedModelSerializer(model=MyModel, fields=fields) viewset = ModelViewSet(queryset=queryset, serializer_class=serializer_class) # Then to register it all with the router: self.register(app_name + '/' + model.__name__, viewset) I get the error: TypeError: __init__() got an unexpected keyword argument 'fields' The problem seems to be that in HyperlinkedModelSerializer, 'model' and 'fields' are normally defined as Meta options so it doesn't seem to accept them when they are provided in this way. Is there a way to achieve this? Thanks. -
Validate special character while entering text in Django model field
I have a django model class Order(AbstractOrder): number = models.CharField( _("Order Number"), max_length=40, db_index=True, unique=True, validators = [ RegexValidator( regex=r'^[-,_\w]*$', message=_("Only AlphaNumerics and , - _ are allowed"))]) I have added the regex check for number field and on click of save it is properly validating, but my requirement is i want to validate it while entering itself, How i can achieve it, how can i integrate js to validate it. -
Invalid column name 'id' in Django
Before you guys start down voting my question, please read the description. So i'm using Django models in a different way, I have existing tables in MS SQL server and I would like to access them for my application. I've been following some tutorials in pluralsights and also https://docs.djangoproject.com/en/1.11/howto/legacy-databases/. I followed the steps accordingly and got my models ready and,when i used 'migrate' command, I got this error “AssertionError: A model can't have more than one AutoField.” So I looked up SO and got another documentation by Django By default, Django gives each model the following field: id = models.AutoField(primary_key=True) This is an auto-incrementing primary key. If you’d like to specify a custom primary key, just specify primary_key=True on one of your fields. If Django sees you’ve explicitly set Field.primary_key, it won’t add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added). So by his solution, i've added 'id' column to the tables which don't have a primary key and skipped the ones which had. And my 'migrate' command worked smooth. But When I'm trying to test if i can get values from it, it shows Invalid column 'ID' Now, … -
django implement filter on in template
i m buiding an in terface (something like phpmyadmin) but more userfriendly...i ve imported all tables but now i want to add sort,filter and search on every table. this is my tables/views.py def table_base(request): table_name = Crawledtables._meta.db_table list_tables = Crawledtables.objects.order_by('id') return render(request, 'tables/table_base.html', {'table_name': table_name, 'list_tables': list_tables}) class AboutDetail(DetailView): model = Crawledtables pk_url_kwarg = 'table_id' template_name = 'tables/table_list.html' def __init__(self, **kwargs): super(AboutDetail, self).__init__(**kwargs) def get_object(self): if 'table_id' not in self.kwargs: return Crawledtables.objects.get(id=1) else: return Crawledtables.objects.get(id=self.kwargs['table_id']) def addview(request, table_id): table_name = Crawledtables.objects.get(id=table_id) tbl_details = "SELECT * FROM " + table_name.name tbl_detail = AllTables.objects.raw(tbl_details) paginator = Paginator(list(tbl_detail), 100) page = request.GET.get('page') try: details = paginator.page(page) except PageNotAnInteger: details = paginator.page(1) except EmptyPage: details = paginator.page(paginator.num_pages) crawled_tables = AllTablesFilter(request.GET, queryset=tbl_detail) return render(request, 'tables/table_list.html', {'tbl_name': table_name, 'details': tbl_detail, 'filter': crawled_tables, 'detail_page': details}) def GeneralSearch(request): table_list = Crawledtables.objects.all() crawled_tables = GeneralFilter(request.GET, queryset=table_list) return render(request, 'tables/table_search.html', {'filter': crawled_tables}) def AllTablesSearch(request, table_id): table_name = Crawledtables.objects.get(id=table_id) tbl_details = "SELECT * FROM " + table_name.name table_list = AllTables.objects.raw(tbl_details) # table_list = Crawledtables.objects.all() crawled_tables = AllTablesFilter(request.GET, queryset=table_list) return render(request, 'tables/alltables_search.html', {'tbl_name': table_name, 'filter': crawled_tables}) this is my tables/filter.py class GeneralFilter(django_filters.FilterSet): class Meta: model = Crawledtables fields = ['name', 'date'] class AllTablesFilter(django_filters.FilterSet): class Meta: model = AllTables fields = ['id','title', 'url','description'] … -
django form widget, compound select
I'm trying to create a form field in django where the user can select the number of years and months, (to ultimately store the number of months - will convert years to months). However I'm not sure of the relevant widget to use in django to achieve this. (or if this needs to be done via more than one widget?) The SelectMultiple widget doesn't appear to be multiple select form fields but instead used to select multiple option in one select. eg see the pic -
Django admin: many-to-one relationships and creation of new "many" object from existing "one"
Django==1.11.5 I have two models: class Sheet(models.Model): canonical_image = models.ForeignKey('images.Image', blank=True, null=True, on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_related", verbose_name=_("canonical image")) class Image(models.Model): sheet = models.ForeignKey(Sheet, on_delete=models.PROTECT, verbose_name=_("sheet")) pass I registered the models for Django admin. Now when I change the sheet in admin, I see "Canonical image" and a plus button to add an image. If I press the plus button, a form for creating a new Image appear. And there is going to be a drop down list with choices sheets. There is a bunch of sheets there. This is clumsy. I press a plus sign from a definite sheet. That very sheet should be selected for creation a new image. Could you tell me how to cope with this problem. Maybe to limit the choice to that particular sheet. Or remove the sheet from image creation form and substitute it in input type="hidden". Or something else. The easier the better. -
how to implement django-easycart in django
how do you implement this https://github.com/nevimov/django-easycart to show items in it. As at now it is showing and empty -
python-memcached installation failed using pip and conda in Python 3.6
python-memcached library failed to installed in Python 3.6 Commands: pip install python-memcached Trace: Collecting python-memcached Downloading python-memcached-1.58.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\JSR\AppData\Local\Temp\pip-build-j63q50jp\python-memcached\setup.py", line 8, in <module> version=get_module_constant('memcache', '__version__'), File "F:\installed\conda2_installed\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\depends.py", line 164, in get_module_constant File "F:\installed\conda2_installed\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\depends.py", line 195, in extract_constant IndexError: tuple index out of range ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\JSR\AppData\Local\Temp\pip-build-j63q50jp\python-memcached\ Commands: conda install -c anaconda python-memcached Trace: Fetching package metadata ............. Solving package specifications: . UnsatisfiableError: The following specifications were found to be in conflict: - python 3.6* - python-memcached -> python 2.7* Use "conda info <package>" to see the dependencies for each package. Command For Info Dependencies: conda info python-memcached Output: python-memcached 1.57 py35_0 file name : python-memcached-1.57-py35_0.tar.bz2 name : python-memcached version : 1.57 build string: py35_0 build number: 0 channel : defaults size : 45 KB arch : x86_64 date : 2015-10-01 license : OSI license_family: PSF md5 : ce80c762e4fcd7aa7b7c1d3aa1e74424 noarch : None platform : win32 url : https://repo.continuum.io/pkgs/free/win-64/python-memcached-1.57-py35_0.tar.bz2 dependencies: python 3.5* six -
Why am I getting ' when AJAX saving (and repopulating) my form in Django
I'm saving a draft of my form using AJAX (and a bit of Angular). <!-- index.html --> ... <input id="id_title" name="title" ng-model="title" placeholder="Question Title" type="text" value="" required /> ... <script> app.controller("addQuestionCtrl", function($http) { $scope.title = '{% if form.title.value is not None %}{{ form.title.value }}{% endif %}'; ... $interval(function() { ... data = {title:''+$scope.title, ...}; $http.post("{% url 'save_draft' %}", data).then(function(response) { ... }, function failureCallback(error) { ... }); }, 10000); }); </script> This is all works fine and sends a ' as a '. In my view.py I convert the data and store it in the session: def save_draft(request): .... posted = json.loads(request.body.decode("utf-8")) ... request.session['draft'] = { 'title': posted.get('title', None), ... } and then populate the relevant fields when the page loads def question_add(request): .... if request.method == 'POST': .... else: draft_question = request.session.get('draft', False) if draft_question: form = QuestionAddForm(initial={ 'title':draft_question['title'], ... }) Unfortunately this turns this into this it's not an encoding issue on the client end as the field renders as <input id="id_title" name="title" ng-model="title" ... value="&#39;title in quotes&#39;" /> I'm not to sure why this is happening :( -
How return list to Json objects with dictionaries?
I have a python list which is structured as l = [{ "Letter": "A", "Freq": 20 }, { "Letter" : "B", "Freq": 12 }] When I return this as a json with json.dumps(l) and parse it in js with JSON.parse(data) I am getting an array. But what I am aiming for is that js parses it as an object. My goal is to render the json part of this tutorial in Django. -
Memory management in Django
I'm doing some analysis on my Django database. I do many queries in a loop and some of these queries may return big results. So, after a while the whole 8 GB of RAM on my EC2 instance is eaten and I cannot even ssh to the machine any longer. I have to reboot the instance then start over again. I tried the solution mentioned here: https://baxeico.wordpress.com/2014/09/30/optimize-django-memory-usage/ But the queryset_iterator method seems not to work with aggregated queries. I'm pretty sure that any single query cannot consume all 8 GB of RAM. So, this means that the old results are not deleted from memory. How do I force a query out of the memory before the end of its loop iteration and before executing the next query? -
How to translate djangocontrib.messages
I'm using django-admin to add and update few models. I translated the django-admin successfully to arabic.( the page, modal names and fields....) The only problem is that django.contrib.messges don't get translated. For example: when I add a new object , I get "%name was changed successfully " in english. Right now, I figured this method: def save_model(self, request, obj, form, change): messages.sucess(request, _('%name changed successfully.')) self.save() But I have to do it to every model, and to every message level (success, info, warning....) Is there a better way ? -
Model Field added using custom SQL not detected by Django
I have added a field to my model. But I have added the field to the model in DB through a custom sql query(Alter Field). Now when I try to create other Migration files, Django creates migration for adding the field to that model in DB. How to make django not do this? -
I want that Django model field can have only two possible values
class Proposta(models.Model): descrizione = models.TextField() titolo = models.CharField(max_length=200) richiedibile = models.BooleanField(default=False) inRichiesta = models.BooleanField(default=False) archiviata = models.BooleanField(default=False) # tesi or AP tipologia = models.CharField(max_length=50) I want that the 'tipologia' field can have only two possible value: 'tesi' or 'AP'. In other words I want the field looks like a list in which user can choose the value he want. -
What's the strange format data in python?
When I use the ajax post to my api, I get the bellow information, I did not saw this data type, who can explain this: {u'params[memory_cpu_address][3][cpu]': u'1\u6838', u'params[bandwidth][bandwidth]': u'1M', u'params[security_setting][example_name]': u'liaodalin01', u'params[memory_cpu_address][2][model]': u'\u6807\u51c6\u578b\u4e00', u'params[server_count][server_length]': u'1\u53f0', u'params[operating_system][system_edition]': u'Windows2003', u'params[memory_cpu_address][0][address]': u'\u6df1\u5733', u'params[security_setting][user_name]': u'root', u'params[storage][data_disk][disk_length]': u'0', u'params[storage][system_disk][type]': u'SSD', u'params[security_setting][user_password]': u'liaodalin01', u'params[memory_cpu_address][4][memory]': u'1G', u'params[total_prices][prices]': u'430', u'params[memory_cpu_address][1][usable-area]': u'\u6df1\u5733\u4e00\u533a', u'params[operating_system][system_name]': u'Windows', u'params[storage][data_disk][type]': u'SSD', u'params[time_buying][deta_time]': u'1\u6708', u'params[storage][system_disk][disk_length]': u'40' } My ajax code is : $.ajax({ type:'post', url:'/app_api/buy_server/', data:{'params':buy_data}, # buy_data is a dictionary in js success:success_func, }) My views.py code is : if request.method == 'POST': post_querydict = request.POST post = post_querydict.dict() print (post) How can I get the normal dictionary format? because this type data, I can not get the data like this post.get("params") method. -
Mocking external library in django
I'm trying to mock external library import in my django app, however tests keep complaining that library is not found. It works fine if I put tests into tests.py file together with the rest of the code, like models.py, urls.py and views.py. However, if I put tests under tests directory, it starts throwing no module named.. exception. I have these two imports in views.py: import xml_to_struc.process import csv_to_struc.process and I have the following in tests to mock them: import sys from unittest.mock import MagicMoc module = MagicMock() sys.modules['xml_to_struc'] = module sys.modules['xml_to_struc.process'] = module sys.modules['csv_to_struc'] = module sys.modules['csv_to_struc.process'] = module As I said, if I put them into tests.py together with the rest of the files, this mocking works fine, but doesn't work if I put them under tests directory. Error message I get: ImportError while importing test module '(...)/converter/urls.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: converter/urls.py:3: in <module> from converter import views converter/views.py:8: in <module> import xml_to_struc.process E ModuleNotFoundError: No module named 'xml_to_struc' How can I mock this import? I've tried mocking in tests/__init__.py, but it looks like import is happening a lot earlier in the process, before mocking.